-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmyscript.js
More file actions
353 lines (312 loc) · 10.6 KB
/
myscript.js
File metadata and controls
353 lines (312 loc) · 10.6 KB
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
var p, q, e, n, phi, d;
// To check if (num) is prime number or not; returns either True or False.
function isPrime(num) {
for (let i = 2, s = num; i * i <= s; i++)
if (num % BigInt(i) === 0) return false;
return num > 1;
}
// Extended Euclidean Algorithm that returns [gcd, inverse].
function egcd(a, b) {
var Phi = b;
if (a < b) [a, b] = [b, a];
let s = BigInt(0), old_s = BigInt(1);
let t = BigInt(1), old_t = BigInt(0);
let r = b, old_r = a;
while (r != 0) {
let q = old_r / r;
[r, old_r] = [old_r - q * r, r];
[s, old_s] = [old_s - q * s, s];
[t, old_t] = [old_t - q * t, t];
}
// If the inverse (old_t = d) is negative, take it's smallest positive coefficient.
if (old_t < BigInt(0)) {
while (old_t < BigInt(0)) {
old_t += Phi;
}
}
return ([old_r, old_t]); // [GCD, Inv]
}
// returns x^y (Mod p) used for {m^e mod n, c^d mod n}.
function powerMod(x, y, p) {
// Initialize result
let res = BigInt(1);
// Update x if it is more
// than or equal to p
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
// If y is odd, multiply
// x with result
if (y & BigInt(1))
res = res * x % p;
// y must be even now
// y = $y/2
y = y / BigInt(2);
x = x * x % p;
}
return res;
}
// For p number in the form.
function check1() {
p = document.getElementById("pValue").value;
console.log(p);
p = BigInt(p);
if (p < 99999999999999) {
if (isPrime(p)) {
console.log(p);
document.getElementById("qValue").removeAttribute("readonly");
console.log("now you can use the second!");
}
else {
alert("Not a prime number!!\nPlease enter another number and it must be prime.");
}
}
else {
console.log(p);
document.getElementById("qValue").removeAttribute("readonly");
console.log("now you can use the second!");
}
}
// For q number in the form.
function check2() {
q = document.getElementById("qValue").value;
q = BigInt(q);
if (q < 99999999999999) {
if (isPrime(q)) {
calculateValues();
document.getElementById("eValue").removeAttribute("readonly");
console.log("now you can use the third!");
}
else {
alert("Not a prime number!!\nPlease enter another number and it must be prime.");
}
}
else {
calculateValues();
document.getElementById("eValue").removeAttribute("readonly");
console.log("now you can use the third!");
}
}
// Calculate n and phi.
function calculateValues() {
n = p * q;
if (p == q)
phi = (p - BigInt(1)) * q;
else
phi = (p - BigInt(1)) * (q - BigInt(1));
console.log("This is p:", p);
console.log("This is q:", q);
console.log("This is n:", n);
console.log("This is phi:", phi);
}
// For e number in the form.
function check3() {
e = document.getElementById("eValue").value;
e = BigInt(e);
// e must be coefficient with phi, and it must be 1 < e < phi.
if (egcd(e, phi)[0] == 1 && e * BigInt(1) > 1 && e * BigInt(1) < phi) {
console.log(e);
document.getElementById("plaintext").removeAttribute("readonly");
calculateD(e, phi);
}
else {
alert("Invalid value of e!!\nPlease enter another number and make sure it is a coprime with phi=" + phi + " and it must be 1 < e < phi.");
console.log("Wrong E!!");
}
}
// To calculate the inverse of e (d); where e*d Mod phi == 1.
function calculateD(E, Phi) {
console.log("This is E and Phi before the algo: ", E, Phi);
d = egcd(e, phi)[1];
console.log("This is d: ", d);
}
var Plain, plainSplit, Cipher, cipherSplit, plainAgain, plainAgainSplit, protocolList = [];
// For plaintext in the form; 1- Convert it to ascii code. 2- Add left 0 for values < 100 ('97' -> '097').
// eg: 'Hello' -> ['H','e','l','l','o'] -> ['072','101','108','108','111'].
function takePlain() {
Plain = document.getElementById("plaintext").value;
console.log("This is the plaintext:", Plain);
plainSplit = Plain.split("");
for (let i = 0; i < plainSplit.length; i++) {
plainSplit[i] = '' + plainSplit[i].charCodeAt(0);
if ('' + plainSplit[i] < 100)
plainSplit[i] = "0" + plainSplit[i];
}
console.log("Plaintext converted to ascii array: ", plainSplit);
console.log("IN PROTOCOL!!");
protocol();
}
// To know how many chars must be in a single block (depends on number of digits of n).
var protocolNum;
function protocol() {
var nTmp = n, len = 3, counter = 1;
nTmp = '' + nTmp;
if (nTmp.length > len) {
var m = n;
counter = 0;
while (m > 1) {
counter++;
m = m / BigInt(10);
}
counter = Math.floor(counter / 3);
}
protocolNum = counter;
console.log("This is protocolNum: ", protocolNum);
prepare();
}
// To convert plaintext list to blocks and adding '000' for each missing character.
// eg considering protocolNum = 2 (each 2 characters in one block):
// ['072','101','108','108','111'] -> ['072101','108108','111000'].
function prepare() {
var tmpSplit = plainSplit;
plainSplit = [];
var st = '' + tmpSplit[0];
for (var i = 1; i < tmpSplit.length; i++) {
if (i % protocolNum == 0) {
plainSplit.push(st);
st = tmpSplit[i];
}
else {
st += tmpSplit[i];
}
}
if (st != tmpSplit[tmpSplit.length - 1]) {
while (st.length < protocolNum * 3) {
st += '0';
}
plainSplit.push(st);
}
else {
plainSplit.push(st);
}
console.log("Plaintext converted to ascii blocks: ", plainSplit, typeof plainSplit[0]);
// We have problem if n < 127, which is m =c^d %(n=50), the values are in the range
// (0 -> 49), while the ascii of any char must be 32 < ascii < 127 which means there are gonna be
// Null values.
if (n < 127)
protocolList1();
else {
for (var i = 0; i < Plain.length; i++)
protocolList.push(0);
}
lowLevelEncryption();
}
// if n < 127 then we want to check how many n are in each ascii floor(ascii/n).
// so when we decrypt the ciphertext we multiply each decrypted-ascii[i] * floor(plain-ascii/n).
function protocolList1() {
for (var i = 0; i < plainSplit.length; i++) {
var div;
div = BigInt(plainSplit[i]) / n;
protocolList.push(div);
}
console.log("This is protocolList: ", protocolList);
};
// We use the formula C = M^e Mod n; where M is each ascii-block of the plaintext.\
// Results cipherSplit which is cipher-ascii-blocks.
function lowLevelEncryption() {
var tmpNum;
cipherSplit = [];
for (var i = 0; i < plainSplit.length; i++) {
tmpNum = BigInt(plainSplit[i]);
tmpNum = powerMod(tmpNum, e, n);
cipherSplit.push('' + tmpNum);
}
highLevelEncryption();
}
// Iterate in cipherSplit (cipher-ascii-blocks) to seperate the block into sigle chars-ascii, then
// we convert each cipher-char-ascii into plain cipher-char (not numbers anymore).
function highLevelEncryption() {
Cipher = '';
for (var i = 0; i < cipherSplit.length; i++) {
var tmpConv = cipherSplit[i][0];
for (var j = 1; j < 3 * protocolNum; j++) {
if (j % 3 == 0) {
tmpConv = parseInt(tmpConv);
if (tmpConv > 126)
tmpConv %= 126;
if (tmpConv < 32)
tmpConv += 32;
Cipher += String.fromCharCode(tmpConv);
tmpConv = cipherSplit[i][j];
}
else {
tmpConv += cipherSplit[i][j];
}
}
tmpConv = parseInt(tmpConv);
if (tmpConv > 126)
tmpConv %= 126;
if (tmpConv < 32)
tmpConv += 32;
Cipher += String.fromCharCode(tmpConv);
}
console.log("This is the ciphertext:", Cipher);
lowLevelDecrypt();
}
//We take the ciphertext block and do the formula M = C^d Mod n; where C is each block in cipherSplit.
//Results plainAgainSplit that contains ascii blocks of the plaintext (decrypted text).
function lowLevelDecrypt() {
console.log("This is cipherSplit in lowleveldec:", cipherSplit);
plainAgainSplit = [];
tmpCipherSplit = cipherSplit;
var tmp = 0;
console.log(cipherSplit);
for (var i = 0; i < tmpCipherSplit.length; i++) {
tmp = BigInt(tmpCipherSplit[i]);
tmp = powerMod(tmp, d, n);
plainAgainSplit.push('' + tmp);
}
console.log(n);
for (var i = 0; i < plainAgainSplit.length; i++) {
var st = '', counter = 0, tmpNum = BigInt(plainAgainSplit[i]);
while (tmpNum >= 1) {
counter++;
tmpNum = tmpNum / BigInt(10);
}
for (var j = 0; j < protocolNum * 3 - counter; j++)
st += '0';
plainAgainSplit[i] = st + plainAgainSplit[i];
}
console.log("This is plainAgainSplit before high-level: ", plainAgainSplit)
highLevelDecryption()
}
//We iterate plainAgainSplit to seperate each block into sigle ascii-chars then convert these ascii-chars
//into chars (Not numbers anymore).
function highLevelDecryption() {
if (protocolNum != 1) {
var tmpSplit = plainAgainSplit;
plainAgainSplit = []
for (var i = 0; i < tmpSplit.length; i++) {
var newNum = tmpSplit[i][0];
for (j = 1; j < protocolNum * 3; j++) {
if (j % 3 == 0) {
if (newNum != '000')
plainAgainSplit.push(newNum);
newNum = tmpSplit[i][j];
}
else {
newNum += tmpSplit[i][j];
}
}
if (newNum != '000')
plainAgainSplit.push(newNum);
}
}
console.log(plainAgainSplit);
plainAgain = '';
var fromProtocolList;
for (var i = 0; i < plainAgainSplit.length; i++) {
if (plainAgainSplit[i] == '000') {
console.log("got you!! :D", i);
continue;
}
fromProtocolList = BigInt(protocolList[i]) * n;
fromProtocolList += BigInt(plainAgainSplit[i]);
if (fromProtocolList != 0)
plainAgain += String.fromCharCode(Number(fromProtocolList));
}
alert("n: " + (n) + "\np: " + (p) + "\nq: " + (q) + "\nphi: " + (phi) + "\ne: " + (e) + "\nPublic Key: (" + (e) + "," + (n) + ")\nPrivate Key: (" + (d) + "," + (phi) + ")");
alert("This is Ciphertext:\n" + Cipher + "\n\nThis is Decrypted text:\n" + plainAgain);
console.log(plainAgain);
}