-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa.js
55 lines (41 loc) · 1.75 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
const bigInt = require('big-integer');
function generateRSAKeys() {
const p = bigInt(61); // First prime number
const q = bigInt(53); // Second prime number
const n = p.multiply(q); // n = p * q
const phi = p.minus(1).multiply(q.minus(1)); // Euler's Totient function phi(n) = (p-1) * (q-1)
const e = bigInt(17); // Public key exponent
const d = e.modInv(phi);
return { publicKey: { e, n }, privateKey: { d, n } };
}
function encryptRSA(message, publicKey) {
const { e, n } = publicKey;
const encryptedChars = [];
for (let i = 0; i < message.length; i++) {
const charCode = bigInt(message.charCodeAt(i)); // Convert character to ASCII code
const encryptedChar = charCode.modPow(e, n); // Encrypt the character
encryptedChars.push(encryptedChar);
}
return encryptedChars; // Return an array of encrypted values
}
function decryptRSA(encryptedChars, privateKey) {
const { d, n } = privateKey;
let decryptedMessage = '';
for (let i = 0; i < encryptedChars.length; i++) {
const decryptedChar = encryptedChars[i].modPow(d, n); // Decrypt the character
decryptedMessage += String.fromCharCode(decryptedChar); // Convert back to character
}
return decryptedMessage; // Return the decrypted string
}
// Example usage
const { publicKey, privateKey } = generateRSAKeys();
console.log("Public Key:", publicKey);
console.log("Private Key:", privateKey);
const plainText = "Jainam";
console.log("Original message:", plainText);
// Encrypt the message
const cipherText = encryptRSA(plainText, publicKey);
console.log("Encrypted text:", cipherText.join(' ')); // Display encrypted values
// Decrypt the message
const decryptedMessage = decryptRSA(cipherText, privateKey);
console.log("Decrypted message:", decryptedMessage);