In the RSA asymmetric cryptography algorithm every user has a public key (n,e) and a private key (d) to send and receive encrypted messages from other users.
To encrypt a message it changes the characters to their ascii codes:
HELLO -> 72-69-76-76-79
and to send the message encrypted with RSA (c), has to calculate
c = m^e % n
for each character m in the message using the public keys n and e.
to decrypt a message that the user receives has to calculate:
m = c^d % n (is the same to say m is congruent to c^d mod n)
to each number c usign the private key d.
A little example:
user Beto got the public keys:
n = 64523
e = 127
and his private key:
d = 15583
if some user wants to send a message to Beto:
ABAC -> 65-66-65-67
to encrypt the message the user had to calculate
65^127 % 64523 = 27725
66^127 % 64523 = 6407
65^127 % 64523 = 27725
67^127 % 64523 = 2523
and the encrypted code was 27725-6407-27725-2523
Beto to decipher the message had to calculate:
27725^15583 % 64523 = 65
6407^15583 % 64523 = 66
27725^15583 % 64523 = 65
2523^15583 % 64523 = 67
and he got the decrypted message 65-66-65-67
=> ABAC
.
Now the question:
I have this code to solve the last part, but I cant use it with big numbers (like the ones in the example):
function getCongruence(c, d, n) {
return Math.pow(c,d) % n;
}
console.log(getCongruence(5,3,7)); // = 6 cuz 5^3=125 and 125 % 7 => 125 - 7*17 = 125 -119
console.log(getCongruence(19,11,17)); // = 8 cuz 19^11=116490258898219 % 17 = 8
console.log(getCongruence(27725,15583,64523)); // should be 65 but it shows NaN
.as-console-wrapper { max-height: 100% !important; top: 0; }
How can I get the result if use big numbers?
Can I use another algorithm to find the answer?
there is a library I can use to do it?