From 87a1547478d67e345a003e4f77563f8ef0ef6a37 Mon Sep 17 00:00:00 2001 From: Dimitri Lozeve Date: Wed, 10 Jun 2020 17:59:32 +0200 Subject: [PATCH] Fix base64 decoding and decipher single-char xor --- src/ex06/main.c | 19 +++++++++++++++---- src/utils.c | 6 +----- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/ex06/main.c b/src/ex06/main.c index 3515bca..ac36e17 100644 --- a/src/ex06/main.c +++ b/src/ex06/main.c @@ -40,7 +40,15 @@ int main(int argc, char *argv[]) { } char input[BUF_SIZE] = {'\0'}; - size_t nread = fread(input, 1, BUF_SIZE, fp); + int c; + size_t nread = 0; + while ((c = fgetc(fp)) != EOF) { + if (c == '\n' || c == '\r') { // ignore newlines + continue; + } + input[nread] = c; + nread++; + } if (nread == 0) { printf("Cannot read any character from file %s\n", filename); return EXIT_FAILURE; @@ -82,11 +90,14 @@ int main(int argc, char *argv[]) { char key[keysize]; for (size_t j = 0; j < keysize; ++j) { - printf("Guessing key character %2zu: ", j); key[j] = best_single_char_xor_key(blocks_count, blocks[j]); - printf("%c\n", key[j]); } - //printf("key: %s\n", key); + printf("Key: %s\n\n", key); + + for (size_t i = 0; i < len; ++i) { + printf("%c", buf[i] ^ key[i % keysize]); + } + putchar('\n'); return EXIT_SUCCESS; } diff --git a/src/utils.c b/src/utils.c index 4889d4c..97f577e 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,7 +1,6 @@ #include "utils.h" #include #include -#include #include unsigned char hex_to_byte(const char c) { @@ -82,6 +81,7 @@ double frequency_score(size_t len, const char buf[static len]) { 0.0673, 0.0894, 0.0268, 0.0106, 0.0183, 0.0019, 0.0172, 0.0011, // space 0.19182}; + // static const double english_freqs[27] = { // // A-Z // 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, @@ -137,14 +137,10 @@ char best_single_char_xor_key(size_t len, unsigned char buf[static len]) { cur[i] = buf[i] ^ c; } double score = frequency_score(len, cur); - //printf("current character: %c, current score: %f\n", c, score); if (score < min_score) { min_score = score; key = c; } - if (isfinite(min_score)) { - printf("current best character: %c, current best score: %f\n", key, min_score); - } } return key;