Created
June 25, 2012 20:34
-
-
Save gialloporpora/2991050 to your computer and use it in GitHub Desktop.
Some functions to understand RSA encryption with *little* numbers
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
findInverse=function(a,b){ | |
n=b;x=0;lastx=1; | |
while (b!= 0){ | |
q=~~(a/b); | |
temp=a; | |
a=b; | |
b=temp % b; | |
temp=x; | |
x= lastx - q*temp; | |
lastx=temp; | |
} | |
if (lastx<0) lastx+=n; | |
if (a!=1) lastx=0; | |
return lastx; | |
} | |
function expmodn(a,b,n){ | |
e=a; | |
for (i=1;i<b;i++) e=e*a % n; | |
return e; | |
} | |
function msgToNumbers(s){ | |
let a=Array(); | |
for (i in s) a.push(s.charCodeAt(i)); | |
return a; | |
} | |
function numbersToMsg(a){ | |
s=''; | |
for (i in a) s+=String.fromCharCode(a[i]); | |
return s; | |
} | |
rsakey=function(e, b){ | |
this.exp=e; | |
this.modulo=b; | |
this.encryptNumbers=function(a){ | |
encripted=Array(); | |
for (i in a) encripted.push(expmodn(a[i], this.exp, this.modulo)); | |
return encripted; | |
} | |
this.encrypt=function(s){ | |
let a=msgToNumbers(s); | |
return numbersToMsg(this.encryptNumbers(a)); | |
} | |
} | |
msg='ciao mondo'; | |
nmsg=msgToNumbers(msg); | |
pubkey=new rsakey(9, 253); | |
pvtkey=new rsakey(49, 253); | |
encmsg=pubkey.encrypt(msg); | |
alert(encmsg); | |
msg2=pvtkey.encrypt(encmsg); | |
alert(msg2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment