-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa.js
90 lines (57 loc) · 1.71 KB
/
rsa.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
let decryptExp;
function gcd(a, h) {
let temp;
while (true) {
temp = a % h;
if (temp == 0) return h;
a = h;
h = temp;
}
}
function generateEncryptionExponent(phi) {
let exp = 47n;
while (gcd(exp, phi) !== 1n) {
exp += 2n;
}
return exp;
}
function computeDecryptionExponent(exp, phi) {
const k = 2n; // A constant value
let decryptExp = BigInt((1n + (k * phi)) / exp);
while (decryptExp < 1n) {
decryptExp += phi;
}
return decryptExp;
}
function encrypt(message, publicKey) {
const { exp, n } = publicKey;
if (message < 0n || message >= n) {
throw new Error(`Condition 0 <= message < n not met. message = ${message}`);
}
if (gcd(message, n) !== 1n) {
throw new Error("Condition gcd(message, n) = 1 not met.");
}
const crypted = message ** exp % n;
return crypted;
}
function decrypt(crypted, secretKey) {
const { d, n } = secretKey;
const message = crypted ** decryptExp % n;
return message;
}
function rsaExample() {
const firstPrime = 191n;
const secondPrime = 223n;
const n = firstPrime * secondPrime;
const phi = (firstPrime - 1n) * (secondPrime - 1n);
const exp = generateEncryptionExponent(phi);
const decryptExp = computeDecryptionExponent(exp, phi);
const publicKey = { exp, n };
const secretKey = { decryptExp, n };
const message = textToNumber("Hi");
const crypted = encrypt(message, publicKey);
const m2 = decrypt(crypted, secretKey);
console.log(numberToText(m2));
// Hi
}
console.log(rsaExample());