Last active
March 11, 2024 08:54
-
-
Save romeokienzler/f76698532b007370f9a24fcaec7ba245 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Not putting any comments, just follow this excellent tutorial | |
https://www.pagedon.com/rsa-explained-simply/programming | |
Some more credits: | |
https://gist.github.com/krzkaczor/0bdba0ee9555659ae5fe | |
https://www.pagedon.com/modular-exponentiation/programming | |
*/ | |
p = 29 | |
q = 31 | |
n = p * q | |
t = (p - 1) * (q - 1) | |
function isPrime(value) { | |
for(var i = 2; i < value; i++) { | |
if(value % i === 0) { | |
return false; | |
} | |
} | |
return value > 1; | |
} | |
e = 1 | |
while (true) { | |
if (!(t % e === 0)) { | |
if (isPrime(e)) { | |
break | |
} | |
} | |
e++ | |
} | |
d = 1 | |
while (true) { | |
if ((d * e) % t !== 1) { | |
d++ | |
} else { | |
break; | |
} | |
} | |
var modexp = function(a, b, n) { | |
a = a % n; | |
var result = 1; | |
var x = a; | |
while(b > 0){ | |
var leastSignificantBit = b % 2; | |
b = Math.floor(b / 2); | |
if (leastSignificantBit == 1) { | |
result = result * x; | |
result = result % n; | |
} | |
x = x * x; | |
x = x % n; | |
} | |
return result; | |
}; | |
function enc(s) { | |
return s.split('').map(function(c) { | |
char_id = c.charCodeAt(0) | |
char_id_enc = modexp(char_id,e,n) | |
//Math.pow(char_id,e) % n | |
return char_id_enc | |
}) | |
} | |
function dec(a) { | |
return a.map(function(char_id_enc) { | |
char_id = modexp(char_id_enc,d,n) | |
return char_id | |
}).map(function(c) { | |
return String.fromCharCode(c) | |
}).join("") | |
} | |
encrypted = enc("This is top - secret") | |
dec(encrypted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this code. Strangely, it seems to break when p = 5 and q = 11