cryptopals_c

cryptopals crypto challenges solutions in pure c
git clone git://git.superpozycja.net/cryptopals_c
Log | Files | Refs | README

commit 03eb6a68660664fdc45934404d1b3a06cc23d51c
parent 9fa92a533c32c17354fee573638b41920f24551f
Author: anna <anna@brokenlove.online>
Date:   Fri, 26 Jul 2024 23:54:44 +0200

c2 fixups, c3 done

Diffstat:
Ms1/c2.c | 30+++++++++++++++---------------
As1/c3.c | 45+++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 60 insertions(+), 15 deletions(-)

diff --git a/s1/c2.c b/s1/c2.c @@ -1,19 +1,19 @@ #include <ba.h> /* see my tools repo for this */ int main(int argc, char* argv[]) { - if(argc != 3) - return -1; - ba* a; - ba* b; - a = ba_from_hex(argv[1]); - b = ba_from_hex(argv[2]); - if (a == NULL || b == NULL) { - return -1; - } - ba_xor(a, b); - ba_fprint(a, stdout, 0); - printf("\n"); - ba_free(a); - ba_free(b); - return 0; + if (argc != 3) + return -1; + ba* a; + ba* b; + a = ba_from_hex(argv[1]); + b = ba_from_hex(argv[2]); + if (a == NULL || b == NULL) { + return -1; + } + ba_xor(a, b); + ba_fprint(a, stdout, 0); + printf("\n"); + ba_free(a); + ba_free(b); + return 0; } diff --git a/s1/c3.c b/s1/c3.c @@ -0,0 +1,45 @@ +#include <ba.h> +#include <stdlib.h> +#include <ctype.h> + +int score_english(ba *text) +{ + int res = 0; + for (int i = 0; i < text->len; i++) + res += isalnum((text->val)[i]) || isspace((text->val)[i]); + return res; +} + +int main(int argc, char* argv[]) { + if (argc != 2) + return -1; + + ba *ct; + ba *key; + ct = ba_from_hex(argv[1]); + uint8_t best_key; + int max = 0; + if (!ct) + return -1; + printf("decrypting...\n"); + for (uint16_t i = 0; i < 0xff; i++) { + char buf[2*(ct->len)]; + snprintf(buf, 16, "%2x", i); + key = ba_from_hex_n(buf, ct->len); + ba_xor(key, ct); + int sc = score_english(key); + if (sc > max) { + max = sc; + best_key = i; + } + } + + char buf[2*(ct->len)]; + snprintf(buf, 16, "%2x", best_key); + key = ba_from_hex_n(buf, ct->len); + ba_xor(key, ct); + ba_fprint_ascii(key, stdout, 0); + printf("\n"); + + ba_free(ct); +}