cryptopals_c

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

commit 96b7d3b9962f77398553b0784b044845dc82c8af
parent 3d2a2afbcc28da6f736c4e1bd5c18558a5d909cc
Author: anna <anna@brokenlove.online>
Date:   Thu, 29 Aug 2024 20:46:48 +0200

c6 finished - might be a lil buggy idc

Diffstat:
Ms1/c6.c | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 90 insertions(+), 1 deletion(-)

diff --git a/s1/c6.c b/s1/c6.c @@ -5,6 +5,88 @@ const char b64table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +float i_c(ba *ct) +{ + unsigned int occur[256]; + unsigned int i; + unsigned int t; + float res; + + res = 0; + memset(occur, 0, sizeof(occur)); + + for (i = 0; i < ct->len; i++) + occur[ct->val[i]]++; + + t = 0; + for (i = 0; i < 256; i++) + t += occur[i] * (occur[i] - 1); + + res = t / (float) (ct->len * (ct->len - 1)); + return res; +} + +float get_i_c_m(ba *ct, unsigned int m) +{ + float res; + int i; + res = 0; + for (i = 0; i < m; i++) { + ba *chunk = (ba *) malloc(sizeof(ba)); + int j; + int k; + + chunk->len = ct->len / m; + chunk->val = (uint8_t *) malloc(sizeof(uint8_t) * chunk->len); + + for (j = 0, k = 0; j <chunk->len && k + i < ct->len; j++, k += m) + chunk->val[j] = ct->val[k + i]; + res += i_c(chunk); + } + return res / m; +} + +unsigned int guess_m(ba *ct) +{ + unsigned int best; + float max; + int m; + + max = 0; + for (m = 1; m < 40; m++) { + float avg; + + avg = get_i_c_m(ct, m); + if (avg > max) { + max = avg; + best = m; + } + } + return best; +} + +void break_m(ba *ct, unsigned int m) +{ + int i; + + for (i = 0; i < m; i++) { + ba *chunk = (ba *) malloc(sizeof(ba)); + int j; + int k; + + chunk->len = ct->len / m; + chunk->val = (uint8_t *) malloc(sizeof(uint8_t) * chunk->len); + + for (j = 0, k = 0; j <chunk->len && k + i < ct->len; j++, k += m) + chunk->val[j] = ct->val[k + i]; + + chunk = decrypt_scxor(chunk); + + for (j = 0, k = 0; j <chunk->len && k + i < ct->len; j++, k += m) + ct->val[k + i] = chunk->val[j]; + } +} + int b64_chunk_to_hex(char **hex, char *b64) { unsigned int val; @@ -76,8 +158,15 @@ int main(int argc, char *argv[]) base64_to_hex(&hex, b64); ct = ba_from_hex(hex); - ba_fprint(ct, stdout, 0); + + int m = guess_m(ct); + + break_m(ct, m); + + ba_fprint_ascii(ct, stdout, 0); printf("\n"); + ba_free(ct); fclose(f); + return 0; }