-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.c
130 lines (110 loc) · 2.22 KB
/
test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Copyright 2018 (c), Neven Sajko. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// Prints all possible single byte XOR codings of a string, sorted by proximity of the
// english letter frequency stats.
#include <ctype.h> // isalnum
#include <stdio.h> // fputc
#include <stdlib.h> // qsort
#include "alphabet/alphabet.h"
#include "buffer/buffer.h"
#include "encoding/encoding.h"
#include "sizeofMacros.h"
#include "xor/xor.h"
typedef struct {
unsigned char key;
buffer *b;
double distance;
} sortingMember;
static sortingMember arr[0xff];
static int
qsortCompar(const void *m1, const void *m2) {
if (((sortingMember *)m1)->distance < ((sortingMember *)m2)->distance) {
return -1;
}
return 1;
}
static void
bruteAndSort(buffer *buf) {
int k;
for (k = 0; k < ARRAY_SIZE(arr); k++) {
unsigned char key = k;
double freqs[alphabetSize];
arr[key].key = key;
arr[key].b = xorAlloc(buf, key);
monographFreqCount(arr[key].b, freqs);
arr[key].distance = monographFreqScore(freqs, sumOfSquares);
}
QSORT(arr, ARRAY_SIZE(arr), qsortCompar);
}
static void
freeArr(void) {
int k;
for (k = 0; k < ARRAY_SIZE(arr); k++) {
bufferFree(arr[k].b);
}
}
static void
pr(buffer *o) {
size_t i;
for (i = 0; i < o->l; i++) {
fputc(o->b[i], stdout);
}
}
static void
printArr(void) {
int i;
for (i = 0; i < ARRAY_SIZE(arr); i++) {
if (arr[i].distance < 0.046875) {
fprintf(stdout, "%20g %2x ", arr[i].distance, arr[i].key);
pr(arr[i].b);
fputc('\n', stdout);
}
}
fputc('\n', stdout);
}
static unsigned char stringBuf[1 << 10];
static void
f(void) {
for (;;) {
buffer si;
int i = 0;
int chr;
for (;;) {
chr = fgetc(stdin);
if (chr == EOF || !isalnum(chr)) {
break;
}
stringBuf[i] = chr;
i++;
}
for (; chr != EOF;) {
chr = fgetc(stdin);
if (isalnum(chr)) {
ungetc(chr, stdin);
break;
}
}
si.b = stringBuf;
si.l = i;
buffer *bufI = hexDecodeAlloc(&si);
if (bufI == NULL) {
fprintf(stderr, "error\n");
return;
}
bruteAndSort(bufI);
pr(&si);
fputc('\n', stdout);
printArr();
bufferFree(bufI);
freeArr();
if (chr == EOF) {
break;
}
}
}
int
main(void) {
f();
return 0;
}