-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
364 lines (346 loc) · 18.8 KB
/
index.html
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
<!DOCTYPE html>
<html>
<head>
<title>TCG Block Cipher</title>
<meta charset="utf-8" />
<style type="text/css">
* { font-size: 20px; }
body { margin: 16px 48px; }
#plain, #cipher { width: 100%; box-sizing: border-box; }
code { color: #0f0; background-color: #000; }
</style>
</head>
<body>
<form autocomplete="on">
<select id="keyFormat">
<option value="0" selected="selected">Auto-detect</option>
<option value="1">Text</option>
<option value="2">Hexadecimal</option>
<option value="3">Base64</option>
</select>
<input type="text" id="key" placeholder="Key" size="32" />
<input type="button" id="generateKey" value="Generate Key" /><br />
<input type="button" id="encrypt" value="Encrypt" />
<input type="button" id="clearPlain" value="Clear" /> Mode:
<select id="mode">
<option value="0">ECB</option>
<option value="1" selected="selected">CTR</option>
</select>
Rounds: <input type="number" id="rounds" min="4" max="16" step="1" style="width:50px;" placeholder="5" />
<input type="checkbox" id="logData" checked="checked" />
<label for="logData">Log data at each step to console</label>
<br />
<input type="text" id="plain" placeholder="Plaintext" /><br />
<input type="button" id="decrypt" value="Decrypt" />
<input type="button" id="clearCipher" value="Clear" />
<select id="cipherFormat">
<option value="0" selected="selected">Auto-detect</option>
<option value="1">Text</option>
<option value="2">Hexadecimal</option>
<option value="3">Base64</option>
</select><br />
<input type="text" id="cipher" placeholder="Ciphertext" /><br />
<input type="reset" value="Reset" />
</form>
<p id="info"></p>
<p id="description">
Triangular Congruential Generator Block Cipher v1.2 by <a href="http://github.com/CharCoding/TCG-Block-Cipher/" title="GitHub">CharCoding</a>, 2018, All Rights Reserved.<br />
<b>DISCLAIMER: </b>I know next to nothing about cryptography and I just committed a sin by "rolling my own crypto". I am not responsible for any important data
leaked through this cipher. Use at your own risk, and use industrial strength RSA or AES for encrypting important information instead.<br />
That being said, you're always welcome to break this cipher and show me how you did it.<br />I tried to comment <a href="https://github.com/CharCoding/TCG-Block-Cipher/blob/master/index.html" title="View Source">my code</a> and write it in a somewhat clear structure, hopefully it helps.<br /><br />
<b>Challenge: </b>Find the key from the following information:<br />
Mode of operation: <code>ECB</code>. Rounds: <code>5</code><br />
<b>Plaintext:</b><br /><br />
<code>Triangular congruential generators differ from LCGs by having an intermediate step that finds the triangular number of the previous output first and using it to calculate the next output. This simple change avoids many of the weaknesses of LCG, such as the n-th least significant bit has a period of 2^n. This is not the case in TCG, as all bits have an equal, maximal period. For a visualization of the said improvement, visit https://jsfiddle.net/CharCoding/f90q2wo0/1/ .</code><br /><br /><b>Ciphertext:</b><br /><br /><code style="overflow-wrap:break-word;word-break:break-all;">Q1LbbKlyzLArWWOZIixCwSaeRz4IphuTep+EC2ALfDDJcsxKGGESsqqexIIhCxGwBnBiSg0mNpYfz+K6fHj1GLfWqPVQyWuGt5lRovmKVtI2Jc4NpjsGRg5UR0JspFimkBWK4oSNYiwHYNfe0nfdV/9b5JCqUSCvTCycjZcvdEztn+Q352qOs1HFp/+0GalYOThiUGpF37ikoRW2ovgalGavr6kPf2Nw/1ILZNSr7BWOw2yxL3QG6jK9ZVL3mUJCRLXGOC8uTQUe/T8A8nxJrHKfujVYqXiKfhieDLHQhNcEKeHMXpG4geDE9LJyFCugis/ujnBK+gjFxg6YS1loXhULUcEb8byK+zXDiJkOLO/jywYuEtjROMlRZy3PplzIHBVYJLPHQyfiVUSapC8h9/y95SAbYxuxu+lkus1eiovaRoSVnXsjQEUTBy4uvN5LExURP/wLVd5pNKrCwINP6Kt7GflH+pSOhX7mwwEVqrL/ZUzuPQ38wqOvMjN47Bg0JLajCMXmnO5kNlcriZWGm6RwIBapaz1cegZG8t6AQQvp/D7yW5xD+MVW88Ol8YN2PRB1QgzMT+AULw545nVWKP2JL3SDYvbWszRYbdQu9wPug+5xEswTMdBD5+kYAUKO</code>
</p>
<script type="text/javascript">'use strict';
/* Triangular Congruential Generator Block Cipher
* Key: 128 bit
* Block: 128 bit
* Structure: SP-network
* Rounds: 4 ~ 16
* Security: none
* Mode of operation: ECB, CTR
* Disclaimer: I am not responsible for any mental or physical damage caused by reading the following code.
*/
const F = 15, FF = 255, FFFF = 65535, FFFFFF = 16777215, // Constants and utility functions
utf8Encode = msg => unescape(encodeURIComponent(msg)), // UTF-8 support
utf8Decode = msg => {
try {
return decodeURIComponent(escape(msg));
} catch(e){
return msg;
}
},
A2S = a => String.fromCharCode(...new Uint8Array(a.buffer)).replace(/\0+$/, ''), // Magic (array to string)
S2A = s => new Uint32Array(Uint8Array.from(s, e => e.charCodeAt(0)).buffer), // More magic (string to array)
A2HEX = a => a.reduce((str, e) => str += e.toString(16).padStart(8, '0'), ''), // Whaaaaat (array to hex)
HEX2A = s => Uint32Array.from(s.replace(/.{1,8}/g, ' 0x$&').split(' ').slice(1)), // It works and I have no idea why (hex to array)
hammingWeight = word => { // count bits set in 32 bit ints
word = word - ((word >> 1) & 1431655765);
word = (word & 858993459) + ((word >> 2) & 858993459);
return ((word + (word >> 4) & 252645135) * 16843009) >>> 24;
}, ROTR = (word, rotation) => word >>> rotation | word << (32 - rotation),
reverseBits = word => {
word = (word >> 1 & 1431655765) | (word & 1431655765) << 1;
word = (word >> 2 & 858993459) | (word & 858993459) << 2;
word = (word >> 4 & 252645135) | (word & 252645135) << 4;
word = (word >> 8 & 16711935) | (word & 16711935) << 8;
return word >>> 16 | word << 16;
}, // Regular expressions for detecting format and replacing control characters
HEXADECIMAL = /^(?:[\da-f]{2})*$/i,
BASE64 = /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=)?$/i,
CONTROLS = /[\0- \x7f]/g,
PICTURES = /[\u2400-\u2420]/g,
DELETE = /\u2421/g;
let debug = +logData.checked; // print each step of calculation to console
/* Main TCG Cipher namespace
* This generator produces m uniformly distributed integers when initialized with the correct parameters.
* Literally the entire cipher relies on the "assumed" lack of correlation between consecutive numbers in the sequence...
* So, if this happens to be not as good as I thought (which probably is the case), the cipher is 100% insecure.
* Otherwise the cipher is 99% insecure.
*/
function* TCG(a, b, m, x){
const i = x;
do yield x = a * (x * x + x >>> 1) + b & m;
while(x != i);
}
// Generator constants for multiplier and adder (128 values * 2 configurations * 65536 starting points = 2^24 sequences)
TCG.A16 = Uint16Array.of(19,21,25,29,31,39,41,43,47,49,53,55,63,67,75,77,83,83,89,91,93,99,107,113,115,117,123,125,127,131,135,141,149,151,157,159,171,173,175,181,193,195,199,209,211,213,219,223,225,227,235,237,239,249,251,259,261,263,267,269,271,279,289,291,299,303,305,311,315,321,331,343,347,351,355,357,359,377,381,383,385,387,389,395,399,403,407,409,413,433,437,441,451,453,459,461,469,471,473,475,477,491,493,503,505,507,509,517,519,521,531,533,535,551,555,557,559,563,571,575,579,581,587,591,595,599,601,603);
TCG.B16 = Uint16Array.of(7027,48722,29554,25898,48703,21679,22404,48667,27421,50846,57678,54379,58499,26801,12849,37470,33019,45563,23642,32973,39758,60063,56613,44510,26783,43934,57369,9214,31739,16427,53951,43566,25122,56247,46232,53147,47357,52188,55259,45866,26558,57649,17231,20062,21897,56702,64117,5269,35366,58599,38833,61604,61409,34594,54241,6641,35436,33811,28759,57962,43583,30493,64588,48941,3871,13457,44596,13573,62497,33676,24865,43943,11953,54443,39025,38414,23359,42764,4564,62827,58522,21765,56806,61667,37519,27881,16021,55870,25436,55052,30894,34226,22893,27772,27569,46106,502,24277,32614,54185,24914,15991,21578,16179,13026,38607,52388,31222,39559,61526,349,46702,49011,45121,64679,14830,21013,3781,9355,41015,33467,19298,52901,28295,47273,37667,22978,43109);
//TCG.A19 = Int8Array.of(7, 11, 13, 19, 23, 29, 37, 47); // long generators have period 2^19
//TCG.B19 = Int32Array.of(14777, 222271, 386462, 506713, 228781, 180182, 89754, 63043);
TCG.A24 = Uint8Array.of(13, 19, 23, 29, 41, 43, 47, 53, 57, 59, 67, 69, 77, 79, 83, 89); // period 2^24
TCG.B24 = Uint32Array.of(9574662, 12161091, 11419271, 488246, 7275484, 13489393, 11220997, 9667556, 7293988, 6796727, 4623555, 3906076, 12813934, 8872101, 9509227, 6151474);
// Cryptographic functions
TCG.padMessage = (str, chunk = 16) => str + new Array(chunk - (str.length - 1 & chunk - 1)).join('\0');
TCG.generator = (gen, seed) => { // return a generator from given parameter and seed
if(gen & 128)
return TCG(65536 - TCG.A16[gen & 127], 32767 ^ TCG.B16[gen & 127], FFFF, seed);
return TCG(TCG.A16[gen], TCG.B16[gen], FFFF, seed);
};
TCG.longGenerator = (gen, seed) => TCG(TCG.A24[gen], TCG.B24[gen], FFFFFF, seed);
TCG.initKey = str => { // If key is too short it is repeated, if key is too long it is added on top
const k = new Uint32Array(4), input = S2A(TCG.padMessage(str, 4));
for(let i = Math.max(input.length, 4); i--;) k[i & 3] += input[i % input.length];
if(debug) TCG.logData(k, 'initKey');
return k;
};
TCG.keygen = k => { // SECURITY THROUGH OBSCURITY REeeEEeEeeEeeEEeEEeeEeEEeEeeEEeE
const HW = hammingWeight(k[0]) + hammingWeight(k[1]) + hammingWeight(k[2]) + hammingWeight(k[3]),
SUM = k[0] + k[1] + k[2] + k[3],
PRODUCT = Math.imul(Math.imul(k[0],k[1]),Math.imul(k[2],k[3])),
G = TCG.longGenerator(HW & F, SUM & FFFFFF), G8 = [
TCG.generator(k[0] & FF, k[1] & FFFF),
TCG.generator(k[0] >>> 8 & FF, k[1] >>> 16),
TCG.generator(k[0] >>> 16 & FF, k[3] & FFFF),
TCG.generator(k[0] >>> 24, k[3] >>> 16),
TCG.generator(k[2] & FF, SUM & FFFF),
TCG.generator(k[2] >>> 8 & FF, SUM >>> 16),
TCG.generator(k[2] >>> 16 & FF,PRODUCT & FFFF),
TCG.generator(k[2] >>> 24, PRODUCT >>> 16) // create 8 TCG generators
], nk = k.map(reverseBits);
for(let i = 32; i--;) {
const temp = G.next().value;
nk[i & 3] ^= ROTR(G8[temp & 7].next().value << 16 ^ temp >>> 3, i); // assign values based on long generator G
}
if(debug) TCG.logData(k, nk, 'keygen');
return nk;
};
TCG.xor = (k, arr) => { // key whitening
for(let i = arr.length; i--;) arr[i] ^= k[i & 3];
if(debug) TCG.logData(arr, 'xor');
};
TCG.add = (k, arr, reverse) => { // used in the middle round
if(reverse)
for(let i = arr.length; i--;) arr[i] -= k[i & 3];
else
for(let i = arr.length; i--;) arr[i] += k[i & 3];
if(debug) TCG.logData(arr, 'add');
}
TCG.sbox = (k, arr, reverse) => { // 16-bit word substitution (Theoretically 2^48 possible outputs)
const gen = ROTR(k[0] << 1 ^ k[1] >>> 1, hammingWeight(k[2])) & FFFF, seed = ~k[2] ^ k[3] << 3 ^ k[3] >>> 4,
G0 = TCG.generator(gen >>> 8, seed >>> 16), G1 = TCG.generator(gen & FF, seed & FFFF),
SBOX = new Uint16Array(65536), before = arr.slice(); // rip memory (32KB dictionary)
if(reverse)
for(let i = 65536; i--;) SBOX[G1.next().value] = G0.next().value;
else
for(let i = 65536; i--;) SBOX[G0.next().value] = G1.next().value;
for(let i = arr.length; i--;) arr[i] = SBOX[arr[i] >>> 16] << 16 | SBOX[arr[i] & FFFF];
if(debug) TCG.logData(before, arr.slice(), 'sbox');
};
TCG.pbox = (k, arr, reverse) => { // 128-bit block permutation (Theoretically 2^28 possible outputs)
const gen = ROTR(k[3] << 2 ^ k[2] >>> 1, hammingWeight(k[1])) & F, seed = reverseBits(k[1]) ^ k[0] << 4 ^ k[0] >>> 3,
G = TCG.longGenerator(gen, seed & FFFFFF), before = arr.slice();
let order = new Array(128);
for(let i = 128; i--;) order[i] = [G.next().value, i]; // bucket sort 128 indices based on generator output
order.sort((a, b) => a[0] - b[0]);
order = Uint8Array.from(order, x => x[1]);
if(reverse)
for(let i = 0, l = arr.length; i < l; i += 4){
const tempArr = arr.slice(i, i + 4);
for(let j = i; j < i + 4; j++) arr[j] = 0;
for(let j = 128; j--;) arr[i + (order[j] >>> 5)] |= ((tempArr[j >>> 5] >>> (j & 31)) & 1) << (order[j] & 31);
}
else
for(let i = 0, l = arr.length; i < l; i += 4){
const tempArr = arr.slice(i, i + 4);
for(let j = i; j < i + 4; j++) arr[j] = 0;
for(let j = 128; j--;) arr[i + (j >>> 5)] |= ((tempArr[order[j] >>> 5] >>> (order[j] & 31)) & 1) << (j & 31);
}
if(debug) TCG.logData(before, arr.slice(), 'pbox');
};
TCG.round = (k, arr, reverse, alternate) => { // round function
if(reverse) {
TCG.pbox(k, arr, reverse);
TCG.sbox(k, arr, reverse);
}
if(alternate) TCG.add(k, arr, reverse);
else TCG.xor(k, arr);
if(!reverse) {
TCG.sbox(k, arr);
TCG.pbox(k, arr);
}
};
TCG.stream = (ks, arr, IV) => { // Stream generator for CTR Mode
const stream = new Uint32Array(arr.length), G = TCG.longGenerator((IV[0] ^ IV[3]) & F, (IV[1] ^ IV[2]) & FFFFFF), before = arr.slice();
for(let i = arr.length; i--;){
stream[i] = IV[i & 3];
if((i & 3) == 3) stream[i] = (stream[i] & 0xff000000) | G.next().value; // maximum length is 2^26 characters in CTR mode
}
if(debug) TCG.logData(IV, 'IV');
for(let i = 0; i < ks.length - 1; i++)
TCG.round(ks[i], stream, false, i == ks.length >> 1);
TCG.xor(ks[ks.length - 1], stream);
TCG.sbox(ks[ks.length - 1], stream);
for(let i = arr.length; i--;)
arr[i] ^= stream[i];
if(debug) TCG.logData(before, arr.slice(), 'stream');
};
TCG.encrypt = data => {
try {
const then = performance.now(), k = TCG.initKey(key.value), // Let's measure the time cuz why not
ks = new Array(+rounds.value || 5);
ks[0] = TCG.keygen(k);
for(let i = 1; i < ks.length; i++)
ks[i] = TCG.keygen(ks[i - 1]);
data = S2A(TCG.padMessage(utf8Encode(data)));
let before = data.slice();
if(+mode.value) { // CTR mode
const IV = crypto.getRandomValues(new Uint32Array(4)),
tempArr = new Uint32Array(data.length + 4);
TCG.stream(ks, data, IV);
tempArr.set(IV);
tempArr.set(data, 4);
data = tempArr;
} else {// ECB mode
for(let i = 0; i < ks.length - 1; i++) {
TCG.round(ks[i], data, false, i == ks.length >> 1);
if(debug) {
TCG.logData(before, data, 'encrypt-' + i);
before = data.slice();
}
}
TCG.xor(ks[ks.length - 1], data);
TCG.sbox(ks[ks.length - 1], data);
if(debug) TCG.logData(before, data, 'encrypt-' + (ks.length - 1));
}
cipher.value = toFormat(data, +cipherFormat.value, true);
info.innerText = 'Encryption successful. (' + (performance.now() - then) + ' ms)';
} catch(err) {
info.innerText = 'Encryption failed: ' + err; // should never happen (famous last words)
}
};
TCG.decrypt = data => {
try {
const then = performance.now(), k = TCG.initKey(key.value),
ks = new Array(+rounds.value || 5);
ks[0] = TCG.keygen(k);
for(let i = 1; i < ks.length; i++)
ks[i] = TCG.keygen(ks[i - 1]);
data = fromFormat(data, +cipherFormat.value, true);
let before = data.slice();
if(+mode.value){ // CTR mode
let IV = data.subarray(0, 4);
data = data.slice(4);
TCG.stream(ks, data, IV);
} else {// ECB mode
TCG.sbox(ks[ks.length - 1], data, true);
TCG.xor(ks[ks.length - 1], data);
for(let i = ks.length - 1; i--;) {
if(debug) {
TCG.logData(before, data, 'decrypt-' + (i + 1));
before = data.slice();
}
TCG.round(ks[i], data, true, i == ks.length >> 1);
}
if(debug) TCG.logData(before, data, 'decrypt-0');
}
plain.value = utf8Decode(A2S(data));
info.innerText = 'Decryption successful. (' + (performance.now() - then) + ' ms)';
} catch(err) {
info.innerText = 'Decryption failed: ' + err;
}
};
TCG.logData = (before, after, method) => { // for cryptanalysis
console.log(+mode.value ? 'CTR' : 'ECB', method || after, 'length: ' + before.length); // mode of cipher, function name, length of input
console.log(A2HEX(before)); // hex representation of input
if(method) console.log(A2HEX(after)); // hex representation if output
console.log(A2S(before)); // ASCII
if(method) console.log(A2S(after));
const total = before.length << 5;
let sumBefore = 0, sumAfter = 0, sumXor = 0;
for(let i = before.length; i--;) { // Count total bits set
sumBefore += hammingWeight(before[i]);
if(method) {
sumAfter += hammingWeight(after[i]);
sumXor += hammingWeight(before[i] ^ after[i]);
}
}
console.log(`INPUT: 0:1 = ${total - sumBefore}:${sumBefore}, ${(sumBefore / total * 100).toFixed(1)}%`); // bits set in input
if(method) {
console.log(`OUTPUT: 0:1 = ${total - sumAfter}:${sumAfter}, ${(sumAfter / total * 100).toFixed(1)}%`); // bits set in output
console.log(`CHANGE: 0:1 = ${total - sumXor}:${sumXor}, ${(sumXor / total * 100).toFixed(1)}%`); // how many bits changed
}
} // I don't actually know how to do cryptanalysis, does this even help?
// Formatting
function fromFormat(str, type, replaceControls){
if(!type) {
if(HEXADECIMAL.test(str)) type = 2;
else if(BASE64.test(str)) type = 3;
}
if(type == 2) return HEX2A(str);
if(type == 3) return S2A(atob(str));
// replaceControls will replace characters that cause problems when rendered as text (DELETE, BACKSPACE, LINE FEED, etc.)
if(replaceControls) str = str.replace(PICTURES, x => String.fromCharCode(x.codePointAt(0) - 9216)).replace(DELETE, '\x7f');
return S2A(str);
}
function toFormat(arr, type, replaceControls){
if(type == 2) return A2HEX(arr);
if(type == 3) return btoa(A2S(arr));
let str = A2S(arr);
if(replaceControls) str = str.replace(CONTROLS, x => String.fromCodePoint(Math.min(x.charCodeAt(0) + 9216, 9249)));
return str;
}
// UI functions
encrypt.addEventListener('click', () => TCG.encrypt(plain.value));
decrypt.addEventListener('click', () => TCG.decrypt(cipher.value));
generateKey.addEventListener('click', () => {
/*// Generating key from third party website is a bad idea. Use local crypto instead.
fetch('https://www.random.org/cgi-bin/randbyte?nbytes=16&format=h', {cache: 'no-store'})
.then(x => x.text())
.then(
x => key.value = toFormat(HEX2A(x.replace(/ /g, '')), +keyFormat.value),
// offline fallback
e => key.value = toFormat(crypto.getRandomValues(new Uint32Array(4)), +keyFormat.value)
).then(() => info.innerText = 'New key generated.')
//*/
key.value = toFormat(crypto.getRandomValues(new Uint32Array(4)), +keyFormat.value);
info.innerText = 'New key generated.';
});
logData.addEventListener('click', e => debug = e.target.checked);
clearPlain.addEventListener('click', () => plain.value = '');
clearCipher.addEventListener('click', () => cipher.value = '');
</script>
</body>
</html>