changed git call from https to git readonly
[atutor.git] / mods / ldap / rsa / rsa.js
1 // Depends on jsbn.js and rng.js
2
3 // convert a (hex) string to a bignum object
4 function parseBigInt(str,r) {
5   return new BigInteger(str,r);
6 }
7
8 function linebrk(s,n) {
9   var ret = "";
10   var i = 0;
11   while(i + n < s.length) {
12     ret += s.substring(i,i+n) + "\n";
13     i += n;
14   }
15   return ret + s.substring(i,s.length);
16 }
17
18 function byte2Hex(b) {
19   if(b < 0x10)
20     return "0" + b.toString(16);
21   else
22     return b.toString(16);
23 }
24
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");
29     return null;
30   }
31   var ba = new Array();
32   var i = s.length - 1;
33   while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);
34   ba[--n] = 0;
35   var rng = new SecureRandom();
36   var x = new Array();
37   while(n > 2) { // random non-zero pad
38     x[0] = 0;
39     while(x[0] == 0) rng.nextBytes(x);
40     ba[--n] = x[0];
41   }
42   ba[--n] = 2;
43   ba[--n] = 0;
44   return new BigInteger(ba);
45 }
46
47 // "empty" RSA key constructor
48 function RSAKey() {
49   this.n = null;
50   this.e = 0;
51   this.d = null;
52   this.p = null;
53   this.q = null;
54   this.dmp1 = null;
55   this.dmq1 = null;
56   this.coeff = null;
57 }
58
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);
64   }
65   else
66     alert("Invalid RSA public key");
67 }
68
69 // Perform raw public operation on "x": return x^e (mod n)
70 function RSADoPublic(x) {
71   return x.modPowInt(this.e, this.n);
72 }
73
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;
82 }
83
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;
88 //}
89
90 // protected
91 RSAKey.prototype.doPublic = RSADoPublic;
92
93 // public
94 RSAKey.prototype.setPublic = RSASetPublic;
95 RSAKey.prototype.encrypt = RSAEncrypt;
96 //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;