1 // Depends on jsbn.js and rng.js
3 // convert a (hex) string to a bignum object
4 function parseBigInt(str,r) {
5 return new BigInteger(str,r);
8 function linebrk(s,n) {
11 while(i + n < s.length) {
12 ret += s.substring(i,i+n) + "\n";
15 return ret + s.substring(i,s.length);
18 function byte2Hex(b) {
20 return "0" + b.toString(16);
22 return b.toString(16);
25 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
26 function pkcs1pad2(s,n) {
27 if(n < s.length + 11) {
28 alert("Message too long for RSA");
33 while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);
35 var rng = new SecureRandom();
37 while(n > 2) { // random non-zero pad
39 while(x[0] == 0) rng.nextBytes(x);
44 return new BigInteger(ba);
47 // "empty" RSA key constructor
59 // Set the public key fields N and e from hex strings
60 function RSASetPublic(N,E) {
61 if(N != null && E != null && N.length > 0 && E.length > 0) {
62 this.n = parseBigInt(N,16);
63 this.e = parseInt(E,16);
66 alert("Invalid RSA public key");
69 // Perform raw public operation on "x": return x^e (mod n)
70 function RSADoPublic(x) {
71 return x.modPowInt(this.e, this.n);
74 // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
75 function RSAEncrypt(text) {
76 var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
77 if(m == null) return null;
78 var c = this.doPublic(m);
79 if(c == null) return null;
80 var h = c.toString(16);
81 if((h.length & 1) == 0) return h; else return "0" + h;
84 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
85 //function RSAEncryptB64(text) {
86 // var h = this.encrypt(text);
87 // if(h) return hex2b64(h); else return null;
91 RSAKey.prototype.doPublic = RSADoPublic;
94 RSAKey.prototype.setPublic = RSASetPublic;
95 RSAKey.prototype.encrypt = RSAEncrypt;
96 //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;