Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Created September 30, 2013 20:31
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 thejefflarson/6769808 to your computer and use it in GitHub Desktop.
Save thejefflarson/6769808 to your computer and use it in GitHub Desktop.
(function(){
// Silly RSA, fun times, if you ever use this I will come to your house and
// punch you.
var gcd = function(a, b) {
var t;
while(b !== 0){
t = b;
b = a % t;
a = t;
}
return a;
};
var modInv = function(a, b) {
if(b === 0) {
return [1, 0];
} else {
var q = Math.floor(a / b);
var r = a % b;
var ret = modInv(b, r);
return [ret[1], ret[0] - q * ret[1]];
}
};
var expMod = function(b, e, mod) {
var result = 1;
while(e > 0) {
if(e % 2 === 1) {
result = (result * b) % mod;
e = e - 1;
}
e = e / 2;
b = (b * b) % mod;
}
return result;
};
var isPrime = function(p){
var a = ((Math.random() * p - 2) | 0) + 2;
return expMod(a, p - 1, p) === 1;
};
var randPrime = function(num){
var p = (Math.random() * num | 0);
while(!isPrime(p) || p < 2)
p = (Math.random() * num | 0);
return p;
};
var KeyPair = function(){
var p = randPrime(100);
var q = randPrime(100);
var n = p * q, tot = (p - 1) * (q - 1);
var e = randPrime(tot);
while(e > 1 && gcd(e, n) !== 1) e = randPrime(tot);
var d = modInv(tot, e)[1];
if(d < 0) d = tot + d;
if(d > tot) d = tot - d;
this.q = q;
this.p = p;
this.d = d;
this.n = n;
this.e = e;
};
KeyPair.prototype.encrypt = function(n){
return expMod(n, this.e, this.n);
};
KeyPair.prototype.decrypt = function(n){
return expMod(n, this.d, this.n);
};
this.KeyPair = KeyPair;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment