This repository was archived by the owner on Jun 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
executable file
·74 lines (60 loc) · 1.5 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
const bigInt = require('big-integer');
class RSA {
static randomPrime(bits) {
const min = bigInt.one.shiftLeft(bits - 1);
const max = bigInt.one.shiftLeft(bits).prev();
while (true) {
let p = bigInt.randBetween(min, max);
if (p.isProbablePrime(256)) {
return p;
}
}
}
static generate(keysize) {
const e = bigInt(65537);
let p;
let q;
let totient;
do {
p = this.randomPrime(keysize / 2);
q = this.randomPrime(keysize / 2);
totient = bigInt.lcm(
p.prev(),
q.prev()
);
} while (bigInt.gcd(e, totient).notEquals(1) || p.minus(q).abs().shiftRight(keysize / 2 - 100).isZero());
return {
e,
n: p.multiply(q),
d: e.modInv(totient),
};
}
static encrypt(encodedMsg, n, e) {
return bigInt(encodedMsg).modPow(e, n);
}
static decrypt(encryptedMsg, d, n) {
return bigInt(encryptedMsg).modPow(d, n);
}
static encode(str) {
const codes = str
.split('')
.map(i => i.charCodeAt())
.join('');
return bigInt(codes);
}
static decode(code) {
const stringified = code.toString();
let string = '';
for (let i = 0; i < stringified.length; i += 2) {
let num = Number(stringified.substr(i, 2));
if (num <= 30) {
string += String.fromCharCode(Number(stringified.substr(i, 3)));
i++;
} else {
string += String.fromCharCode(num);
}
}
return string;
}
}
module.exports = RSA;