-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (77 loc) · 1.68 KB
/
index.js
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
var prompt = require("prompt");
var { chunk } = require("lodash");
prompt.start();
prompt.get(["p", "q", "e", "d", "message"], function (err, result) {
const { p, q, e, d, message } = result;
console.log(`Encrypting "${message}"`);
const encoded = encode(message);
console.log("encoded:", encoded);
const PublicKey = {
n: BigInt(p * q),
e: BigInt(e),
};
console.log("public key", PublicKey);
const PrivateKey = {
d: BigInt(d),
};
console.log("private key", PrivateKey);
const ciphertext = encoded.map((char) => {
return char ** PublicKey.e % PublicKey.n;
});
console.log("ciphertext", ciphertext);
const decrypted = ciphertext.map((char) => {
return char ** PrivateKey.d % PublicKey.n;
});
console.log("decrypted", decrypted);
const decoded = decode(decrypted);
console.log(`decoded: ${decoded}`);
});
// Returns an array of each letter encoded
const encode = (message) => {
return message.split("").map((a) => BigInt(basicEncodingTable[a]));
};
// Decodes each item in the array back into a letter
const decode = (characters) => {
const table = reverseEncodingTable();
return characters
.map((char) => {
return table[char];
})
.join("");
};
const reverseEncodingTable = () => {
const table = {};
Object.keys(basicEncodingTable).forEach((character) => {
const value = basicEncodingTable[character];
table[value] = character;
});
return table;
};
const basicEncodingTable = {
a: 10,
b: 11,
c: 12,
d: 13,
e: 14,
f: 15,
g: 16,
h: 17,
i: 18,
j: 19,
k: 20,
l: 21,
m: 22,
n: 23,
o: 24,
p: 25,
q: 26,
r: 27,
s: 28,
t: 29,
u: 30,
v: 31,
w: 32,
x: 33,
y: 34,
z: 35,
};