| 1 |
define([ |
| 2 |
"dojo/_base/kernel", |
| 3 |
"dojo/_base/declare", |
| 4 |
"../../math/BigInteger", |
| 5 |
"../../math/random/Simple" |
| 6 |
], function(kernel, declare, BigInteger, Simple) { |
| 7 |
|
| 8 |
kernel.experimental("dojox.encoding.crypto.RSAKey"); |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
var defaultRngf = function(){ return new Simple(); }; |
| 15 |
|
| 16 |
|
| 17 |
function pkcs1pad2(s, n, rngf) { |
| 18 |
if(n < s.length + 11) { |
| 19 |
throw new Error("Message too long for RSA"); |
| 20 |
} |
| 21 |
var ba = new Array(n); |
| 22 |
var i = s.length; |
| 23 |
while(i && n) ba[--n] = s.charCodeAt(--i); |
| 24 |
ba[--n] = 0; |
| 25 |
var rng = rngf(); |
| 26 |
var x = [0]; |
| 27 |
while(n > 2) { |
| 28 |
x[0] = 0; |
| 29 |
while(x[0] == 0) rng.nextBytes(x); |
| 30 |
ba[--n] = x[0]; |
| 31 |
} |
| 32 |
ba[--n] = 2; |
| 33 |
ba[--n] = 0; |
| 34 |
rng.destroy(); |
| 35 |
return new BigInteger(ba); |
| 36 |
} |
| 37 |
|
| 38 |
return declare("dojox.encoding.crypto.RSAKey", null, { |
| 39 |
constructor: function(rngf){ |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
this.rngf = rngf || defaultRngf; |
| 46 |
this.e = 0; |
| 47 |
this.n = this.d = this.p = this.q = this.dmp1 = this.dmq1 = this.coeff = null; |
| 48 |
}, |
| 49 |
|
| 50 |
setPublic: function(N, E){ |
| 51 |
|
| 52 |
|
| 53 |
if(N && E && N.length && E.length) { |
| 54 |
this.n = new BigInteger(N, 16); |
| 55 |
this.e = parseInt(E, 16); |
| 56 |
}else{ |
| 57 |
throw new Error("Invalid RSA public key"); |
| 58 |
} |
| 59 |
}, |
| 60 |
|
| 61 |
encrypt: function(text){ |
| 62 |
var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3, this.rngf); |
| 63 |
if(!m){ |
| 64 |
return null; |
| 65 |
} |
| 66 |
var c = m.modPowInt(this.e, this.n); |
| 67 |
if(!c){ |
| 68 |
return null; |
| 69 |
} |
| 70 |
var h = c.toString(16); |
| 71 |
return h.length % 2 ? "0" + h : h; |
| 72 |
} |
| 73 |
}); |
| 74 |
}); |