c6.c (1212B)
1 #include <stdio.h> 2 #include <ctype.h> 3 #include <ba.h> 4 #include <analysis.h> 5 #include <util.h> 6 7 void break_w_keylen(ba *ct, unsigned int m) 8 { 9 int i; 10 11 for (i = 0; i < m; i++) { 12 ba *chunk = (ba *) malloc(sizeof(ba)); 13 int j; 14 int k; 15 16 chunk->len = ct->len / m; 17 chunk->val = (uint8_t *) malloc(sizeof(uint8_t) * chunk->len); 18 19 for (j = 0, k = 0; j <chunk->len && k + i < ct->len; j++, k += m) 20 chunk->val[j] = ct->val[k + i]; 21 22 chunk = decrypt_scxor(chunk); 23 24 for (j = 0, k = 0; j <chunk->len && k + i < ct->len; j++, k += m) 25 ct->val[k + i] = chunk->val[j]; 26 } 27 } 28 29 30 /* use coincidence test to determine the key */ 31 int main(int argc, char *argv[]) 32 { 33 char line[256]; 34 char *b64; 35 char *hex; 36 FILE *f; 37 ba *ct; 38 int sz; 39 40 b64 = (char *) malloc(sizeof(char)); 41 42 f = fopen(argv[1], "r"); 43 if (!f) 44 fprintf(stderr, "error opening file\n"); 45 46 sz = 1; 47 while (fgets(line, sizeof(line), f)) { 48 sz += strlen(line) - 1; 49 b64 = (char *) realloc(b64, sz); 50 strncat(b64, line, strlen(line) - 1); 51 } 52 53 base64_to_hex(&hex, b64); 54 ct = ba_from_hex(hex); 55 56 int m = guess_vigenere_keylen(ct); 57 58 break_w_keylen(ct, m); 59 60 ba_fprint_ascii(ct, stdout, 0); 61 printf("\n"); 62 63 ba_free(ct); 64 fclose(f); 65 return 0; 66 }