1// Depends on jsbn.js and rng.js 2 3// Version 1.1: support utf-8 encoding in pkcs1pad2 4 5// convert a (hex) string to a bignum object 6function parseBigInt(str,r) { 7 return new BigInteger(str,r); 8} 9 10function linebrk(s,n) { 11 var ret = ""; 12 var i = 0; 13 while(i + n < s.length) { 14 ret += s.substring(i,i+n) + "\n"; 15 i += n; 16 } 17 return ret + s.substring(i,s.length); 18} 19 20function byte2Hex(b) { 21 if(b < 0x10) 22 return "0" + b.toString(16); 23 else 24 return b.toString(16); 25} 26 27// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint 28function pkcs1pad2(s,n) { 29 if(n < s.length + 11) { // TODO: fix for utf-8 30 alert("Message too long for RSA"); 31 return null; 32 } 33 var ba = new Array(); 34 var i = s.length - 1; 35 while(i >= 0 && n > 0) { 36 var c = s.charCodeAt(i--); 37 if(c < 128) { // encode using utf-8 38 ba[--n] = c; 39 } 40 else if((c > 127) && (c < 2048)) { 41 ba[--n] = (c & 63) | 128; 42 ba[--n] = (c >> 6) | 192; 43 } 44 else { 45 ba[--n] = (c & 63) | 128; 46 ba[--n] = ((c >> 6) & 63) | 128; 47 ba[--n] = (c >> 12) | 224; 48 } 49 } 50 ba[--n] = 0; 51 var rng = new SecureRandom(); 52 var x = new Array(); 53 while(n > 2) { // random non-zero pad 54 x[0] = 0; 55 while(x[0] == 0) rng.nextBytes(x); 56 ba[--n] = x[0]; 57 } 58 ba[--n] = 2; 59 ba[--n] = 0; 60 return new BigInteger(ba); 61} 62 63// "empty" RSA key constructor 64function RSAKey() { 65 this.n = null; 66 this.e = 0; 67 this.d = null; 68 this.p = null; 69 this.q = null; 70 this.dmp1 = null; 71 this.dmq1 = null; 72 this.coeff = null; 73} 74 75// Set the public key fields N and e from hex strings 76function RSASetPublic(N,E) { 77 if(N != null && E != null && N.length > 0 && E.length > 0) { 78 this.n = parseBigInt(N,16); 79 this.e = parseInt(E,16); 80 } 81 else 82 alert("Invalid RSA public key"); 83} 84 85// Perform raw public operation on "x": return x^e (mod n) 86function RSADoPublic(x) { 87 return x.modPowInt(this.e, this.n); 88} 89 90// Return the PKCS#1 RSA encryption of "text" as an even-length hex string 91function RSAEncrypt(text) { 92 var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); 93 if(m == null) return null; 94 var c = this.doPublic(m); 95 if(c == null) return null; 96 var h = c.toString(16); 97 if((h.length & 1) == 0) return h; else return "0" + h; 98} 99 100// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string 101//function RSAEncryptB64(text) { 102// var h = this.encrypt(text); 103// if(h) return hex2b64(h); else return null; 104//} 105 106// protected 107RSAKey.prototype.doPublic = RSADoPublic; 108 109// public 110RSAKey.prototype.setPublic = RSASetPublic; 111RSAKey.prototype.encrypt = RSAEncrypt; 112//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.