Skip to content

Instantly share code, notes, and snippets.

@romeokienzler
Last active March 11, 2024 08:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romeokienzler/f76698532b007370f9a24fcaec7ba245 to your computer and use it in GitHub Desktop.
Save romeokienzler/f76698532b007370f9a24fcaec7ba245 to your computer and use it in GitHub Desktop.
/*
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)
@MysteryPancake
Copy link

MysteryPancake commented Apr 30, 2021

Thanks for this code. Strangely, it seems to break when p = 5 and q = 11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment