// depends on jsbn.js and rng.js // version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object function parsebigint(str,r) { return new biginteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2hex(b) { if(b < 0x10) return "0" + b.tostring(16); else return b.tostring(16); } // pkcs#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { // todo: fix for utf-8 alert("message too long for rsa"); return null; } var ba = new array(); var i = s.length - 1; while(i >= 0 && n > 0) { var c = s.charcodeat(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new securerandom(); var x = new array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextbytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new biginteger(ba); } // "empty" rsa key constructor function rsakey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // set the public key fields n and e from hex strings function rsasetpublic(n,e) { if(n != null && e != null && n.length > 0 && e.length > 0) { this.n = parsebigint(n,16); this.e = parseint(e,16); } else alert("invalid rsa public key"); } // perform raw public operation on "x": return x^e (mod n) function rsadopublic(x) { return x.modpowint(this.e, this.n); } // return the pkcs#1 rsa encryption of "text" as an even-length hex string function rsaencrypt(text) { var m = pkcs1pad2(text,(this.n.bitlength()+7)>>3); if(m == null) return null; var c = this.dopublic(m); if(c == null) return null; var h = c.tostring(16); if((h.length & 1) == 0) return h; else return "0" + h; } // return the pkcs#1 rsa encryption of "text" as a base64-encoded string //function rsaencryptb64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; //} // protected rsakey.prototype.dopublic = rsadopublic; // public rsakey.prototype.setpublic = rsasetpublic; rsakey.prototype.encrypt = rsaencrypt; //rsakey.prototype.encrypt_b64 = rsaencryptb64;