made encoder and decoder for the secret byte array to use as printable string
sophuwu sophie@sophuwu.site
Fri, 06 Oct 2023 09:10:07 +0200
1 files changed,
41 insertions(+),
10 deletions(-)
jump to
M
main.cpp
→
main.cpp
@@ -1,26 +1,46 @@
#include <fstream> +#include <chrono> +#include <cstring> -const char* chars16 = "0123456789ABCDEF"; +char base16[] = "0123456789ABCDEF"; -struct secret { - char bytes[16]; +struct Secret { + unsigned char bytes[16]; + + char* encode() { + static char s[33]; + for (int i = 0; i < 16; i++) { + s[i*2] = base16[(bytes[i] >> 4) & 15]; + s[i*2+1] = base16[bytes[i] & 15]; + } + s[32] = '\0'; + return s; + } + + void decode(char* s){ + for(int i = 0; i < 16; i++) { + bytes[i] = ((strchr(base16, s[i*2]) - base16) << 4) + | (strchr(base16, s[i*2+1]) - base16); + } + } void load(char* file) { FILE* f = fopen(file, "r"); - fread(secret, 1, 16, f); + fread(bytes, 1, 16, f); fclose(f); } void save(char* file) { FILE* f = fopen(file, "w"); - fwrite(secret, 1, 16, f); + fwrite(bytes, 1, 16, f); fclose(f); } void generate() { + std::srand(std::chrono::high_resolution_clock::now().time_since_epoch().count()); int r, i, j; for (i = 0; i < 16; i += 4) { - r = rand(); + r = std::rand(); for (j = 0; j < 4; j++) { bytes[i + j] = r & 255; r >>= 8;@@ -29,14 +49,25 @@ }
} }; -stuct otp { +struct otp { }; int main() { - secret s; - s.generate(); + Secret secret; + + secret.generate(); + for (int i = 0; i < 16; i++) { + printf("%u ", secret.bytes[i]); + } + char* s = secret.encode(); + printf("\n%s\n", s); + secret.decode(s); for (int i = 0; i < 16; i++) { - printf("%c%c", chars16[s.bytes[i] >> 4], chars16[s.bytes[i] & 15]); + printf("%u ", secret.bytes[i]); } + s = secret.encode(); + printf("\n%s\n", s); + + return 0; }