2 * Copyright (c) 2003-2005 Tom Wu
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
18 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
20 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
21 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
22 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
23 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
24 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * In addition, the following condition applies:
28 * All redistributions must retain an intact copy of this copyright notice
33 // The code has been adapted for use as a benchmark by Google.
34 var Crypto = new BenchmarkSuite('Crypto', [266181], [
35 new Benchmark("Encrypt", true, false, encrypt),
36 new Benchmark("Decrypt", true, false, decrypt)
40 // Basic JavaScript BN library - subset useful for RSA encryption.
53 // JavaScript engine analysis
54 var canary = 0xdeadbeefcafe;
55 var j_lm = ((canary&0xffffff)==0xefcafe);
57 // (public) Constructor
58 function BigInteger(a,b,c) {
59 this.array = new Array();
61 if("number" == typeof a) this.fromNumber(a,b,c);
62 else if(b == null && "string" != typeof a) this.fromString(a,256);
63 else this.fromString(a,b);
66 // return new, unset BigInteger
67 function nbi() { return new BigInteger(null); }
69 // am: Compute w_j += (x*this_i), propagate carries,
70 // c is initial carry, returns final carry.
71 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
72 // We need to select the fastest one that works in this environment.
74 // am1: use a single mult and divide to get the high bits,
75 // max digit bits should be 26 because
76 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
77 function am1(i,x,w,j,c,n) {
78 var this_array = this.array;
79 var w_array = w.array;
81 var v = x*this_array[i++]+w_array[j]+c;
82 c = Math.floor(v/0x4000000);
83 w_array[j++] = v&0x3ffffff;
88 // am2 avoids a big mult-and-extract completely.
89 // Max digit bits should be <= 30 because we do bitwise ops
90 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
91 function am2(i,x,w,j,c,n) {
92 var this_array = this.array;
93 var w_array = w.array;
94 var xl = x&0x7fff, xh = x>>15;
96 var l = this_array[i]&0x7fff;
97 var h = this_array[i++]>>15;
99 l = xl*l+((m&0x7fff)<<15)+w_array[j]+(c&0x3fffffff);
100 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
101 w_array[j++] = l&0x3fffffff;
106 // Alternately, set max digit bits to 28 since some
107 // browsers slow down when dealing with 32-bit numbers.
108 function am3(i,x,w,j,c,n) {
109 var this_array = this.array;
110 var w_array = w.array;
112 var xl = x&0x3fff, xh = x>>14;
114 var l = this_array[i]&0x3fff;
115 var h = this_array[i++]>>14;
117 l = xl*l+((m&0x3fff)<<14)+w_array[j]+c;
118 c = (l>>28)+(m>>14)+xh*h;
119 w_array[j++] = l&0xfffffff;
124 // This is tailored to VMs with 2-bit tagging. It makes sure
125 // that all the computations stay within the 29 bits available.
126 function am4(i,x,w,j,c,n) {
127 var this_array = this.array;
128 var w_array = w.array;
130 var xl = x&0x1fff, xh = x>>13;
132 var l = this_array[i]&0x1fff;
133 var h = this_array[i++]>>13;
135 l = xl*l+((m&0x1fff)<<13)+w_array[j]+c;
136 c = (l>>26)+(m>>13)+xh*h;
137 w_array[j++] = l&0x3ffffff;
142 // am3/28 is best for SM, Rhino, but am4/26 is best for v8.
143 // Kestrel (Opera 9.5) gets its best result with am4/26.
144 // IE7 does 9% better with am3/28 than with am4/26.
145 // Firefox (SM) gets 10% faster with am3/28 than with am4/26.
147 setupEngine = function(fn, bits) {
148 BigInteger.prototype.am = fn;
152 BI_DM = ((1<<dbits)-1);
156 BI_FV = Math.pow(2,BI_FP);
158 BI_F2 = 2*dbits-BI_FP;
163 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
164 var BI_RC = new Array();
166 rr = "0".charCodeAt(0);
167 for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
168 rr = "a".charCodeAt(0);
169 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
170 rr = "A".charCodeAt(0);
171 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
173 function int2char(n) { return BI_RM.charAt(n); }
174 function intAt(s,i) {
175 var c = BI_RC[s.charCodeAt(i)];
176 return (c==null)?-1:c;
179 // (protected) copy this to r
180 function bnpCopyTo(r) {
181 var this_array = this.array;
182 var r_array = r.array;
184 for(var i = this.t-1; i >= 0; --i) r_array[i] = this_array[i];
189 // (protected) set from integer value x, -DV <= x < DV
190 function bnpFromInt(x) {
191 var this_array = this.array;
194 if(x > 0) this_array[0] = x;
195 else if(x < -1) this_array[0] = x+DV;
199 // return bigint initialized to value
200 function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
202 // (protected) set from string and radix
203 function bnpFromString(s,b) {
204 var this_array = this.array;
207 else if(b == 8) k = 3;
208 else if(b == 256) k = 8; // byte array
209 else if(b == 2) k = 1;
210 else if(b == 32) k = 5;
211 else if(b == 4) k = 2;
212 else { this.fromRadix(s,b); return; }
215 var i = s.length, mi = false, sh = 0;
217 var x = (k==8)?s[i]&0xff:intAt(s,i);
219 if(s.charAt(i) == "-") mi = true;
224 this_array[this.t++] = x;
225 else if(sh+k > BI_DB) {
226 this_array[this.t-1] |= (x&((1<<(BI_DB-sh))-1))<<sh;
227 this_array[this.t++] = (x>>(BI_DB-sh));
230 this_array[this.t-1] |= x<<sh;
232 if(sh >= BI_DB) sh -= BI_DB;
234 if(k == 8 && (s[0]&0x80) != 0) {
236 if(sh > 0) this_array[this.t-1] |= ((1<<(BI_DB-sh))-1)<<sh;
239 if(mi) BigInteger.ZERO.subTo(this,this);
242 // (protected) clamp off excess high words
243 function bnpClamp() {
244 var this_array = this.array;
245 var c = this.s&BI_DM;
246 while(this.t > 0 && this_array[this.t-1] == c) --this.t;
249 // (public) return string representation in given radix
250 function bnToString(b) {
251 var this_array = this.array;
252 if(this.s < 0) return "-"+this.negate().toString(b);
255 else if(b == 8) k = 3;
256 else if(b == 2) k = 1;
257 else if(b == 32) k = 5;
258 else if(b == 4) k = 2;
259 else return this.toRadix(b);
260 var km = (1<<k)-1, d, m = false, r = "", i = this.t;
261 var p = BI_DB-(i*BI_DB)%k;
263 if(p < BI_DB && (d = this_array[i]>>p) > 0) { m = true; r = int2char(d); }
266 d = (this_array[i]&((1<<p)-1))<<(k-p);
267 d |= this_array[--i]>>(p+=BI_DB-k);
270 d = (this_array[i]>>(p-=k))&km;
271 if(p <= 0) { p += BI_DB; --i; }
274 if(m) r += int2char(d);
281 function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
284 function bnAbs() { return (this.s<0)?this.negate():this; }
286 // (public) return + if this > a, - if this < a, 0 if equal
287 function bnCompareTo(a) {
288 var this_array = this.array;
289 var a_array = a.array;
296 while(--i >= 0) if((r=this_array[i]-a_array[i]) != 0) return r;
300 // returns bit length of the integer x
303 if((t=x>>>16) != 0) { x = t; r += 16; }
304 if((t=x>>8) != 0) { x = t; r += 8; }
305 if((t=x>>4) != 0) { x = t; r += 4; }
306 if((t=x>>2) != 0) { x = t; r += 2; }
307 if((t=x>>1) != 0) { x = t; r += 1; }
311 // (public) return the number of bits in "this"
312 function bnBitLength() {
313 var this_array = this.array;
314 if(this.t <= 0) return 0;
315 return BI_DB*(this.t-1)+nbits(this_array[this.t-1]^(this.s&BI_DM));
318 // (protected) r = this << n*DB
319 function bnpDLShiftTo(n,r) {
320 var this_array = this.array;
321 var r_array = r.array;
323 for(i = this.t-1; i >= 0; --i) r_array[i+n] = this_array[i];
324 for(i = n-1; i >= 0; --i) r_array[i] = 0;
329 // (protected) r = this >> n*DB
330 function bnpDRShiftTo(n,r) {
331 var this_array = this.array;
332 var r_array = r.array;
333 for(var i = n; i < this.t; ++i) r_array[i-n] = this_array[i];
334 r.t = Math.max(this.t-n,0);
338 // (protected) r = this << n
339 function bnpLShiftTo(n,r) {
340 var this_array = this.array;
341 var r_array = r.array;
345 var ds = Math.floor(n/BI_DB), c = (this.s<<bs)&BI_DM, i;
346 for(i = this.t-1; i >= 0; --i) {
347 r_array[i+ds+1] = (this_array[i]>>cbs)|c;
348 c = (this_array[i]&bm)<<bs;
350 for(i = ds-1; i >= 0; --i) r_array[i] = 0;
357 // (protected) r = this >> n
358 function bnpRShiftTo(n,r) {
359 var this_array = this.array;
360 var r_array = r.array;
362 var ds = Math.floor(n/BI_DB);
363 if(ds >= this.t) { r.t = 0; return; }
367 r_array[0] = this_array[ds]>>bs;
368 for(var i = ds+1; i < this.t; ++i) {
369 r_array[i-ds-1] |= (this_array[i]&bm)<<cbs;
370 r_array[i-ds] = this_array[i]>>bs;
372 if(bs > 0) r_array[this.t-ds-1] |= (this.s&bm)<<cbs;
377 // (protected) r = this - a
378 function bnpSubTo(a,r) {
379 var this_array = this.array;
380 var r_array = r.array;
381 var a_array = a.array;
382 var i = 0, c = 0, m = Math.min(a.t,this.t);
384 c += this_array[i]-a_array[i];
385 r_array[i++] = c&BI_DM;
392 r_array[i++] = c&BI_DM;
401 r_array[i++] = c&BI_DM;
407 if(c < -1) r_array[i++] = BI_DV+c;
408 else if(c > 0) r_array[i++] = c;
413 // (protected) r = this * a, r != this,a (HAC 14.12)
414 // "this" should be the larger one if appropriate.
415 function bnpMultiplyTo(a,r) {
416 var this_array = this.array;
417 var r_array = r.array;
418 var x = this.abs(), y = a.abs();
419 var y_array = y.array;
423 while(--i >= 0) r_array[i] = 0;
424 for(i = 0; i < y.t; ++i) r_array[i+x.t] = x.am(0,y_array[i],r,i,0,x.t);
427 if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
430 // (protected) r = this^2, r != this (HAC 14.16)
431 function bnpSquareTo(r) {
433 var x_array = x.array;
434 var r_array = r.array;
437 while(--i >= 0) r_array[i] = 0;
438 for(i = 0; i < x.t-1; ++i) {
439 var c = x.am(i,x_array[i],r,2*i,0,1);
440 if((r_array[i+x.t]+=x.am(i+1,2*x_array[i],r,2*i+1,c,x.t-i-1)) >= BI_DV) {
441 r_array[i+x.t] -= BI_DV;
442 r_array[i+x.t+1] = 1;
445 if(r.t > 0) r_array[r.t-1] += x.am(i,x_array[i],r,2*i,0,1);
450 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
451 // r != q, this != m. q or r may be null.
452 function bnpDivRemTo(m,q,r) {
454 if(pm.t <= 0) return;
457 if(q != null) q.fromInt(0);
458 if(r != null) this.copyTo(r);
461 if(r == null) r = nbi();
462 var y = nbi(), ts = this.s, ms = m.s;
463 var pm_array = pm.array;
464 var nsh = BI_DB-nbits(pm_array[pm.t-1]); // normalize modulus
465 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
466 else { pm.copyTo(y); pt.copyTo(r); }
469 var y_array = y.array;
470 var y0 = y_array[ys-1];
472 var yt = y0*(1<<BI_F1)+((ys>1)?y_array[ys-2]>>BI_F2:0);
473 var d1 = BI_FV/yt, d2 = (1<<BI_F1)/yt, e = 1<<BI_F2;
474 var i = r.t, j = i-ys, t = (q==null)?nbi():q;
477 var r_array = r.array;
478 if(r.compareTo(t) >= 0) {
482 BigInteger.ONE.dlShiftTo(ys,t);
483 t.subTo(y,y); // "negative" y so we can replace sub with am later
484 while(y.t < ys) y_array[y.t++] = 0;
486 // Estimate quotient digit
487 var qd = (r_array[--i]==y0)?BI_DM:Math.floor(r_array[i]*d1+(r_array[i-1]+e)*d2);
488 if((r_array[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
491 while(r_array[i] < --qd) r.subTo(t,r);
496 if(ts != ms) BigInteger.ZERO.subTo(q,q);
500 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
501 if(ts < 0) BigInteger.ZERO.subTo(r,r);
504 // (public) this mod a
507 this.abs().divRemTo(a,null,r);
508 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
512 // Modular reduction using "classic" algorithm
513 function Classic(m) { this.m = m; }
514 function cConvert(x) {
515 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
518 function cRevert(x) { return x; }
519 function cReduce(x) { x.divRemTo(this.m,null,x); }
520 function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
521 function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
523 Classic.prototype.convert = cConvert;
524 Classic.prototype.revert = cRevert;
525 Classic.prototype.reduce = cReduce;
526 Classic.prototype.mulTo = cMulTo;
527 Classic.prototype.sqrTo = cSqrTo;
529 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
533 // xy(2-xy) = (1+km)(1-km)
534 // x[y(2-xy)] = 1-k^2m^2
535 // x[y(2-xy)] == 1 (mod m^2)
536 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
537 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
538 // JS multiply "overflows" differently from C/C++, so care is needed here.
539 function bnpInvDigit() {
540 var this_array = this.array;
541 if(this.t < 1) return 0;
542 var x = this_array[0];
543 if((x&1) == 0) return 0;
544 var y = x&3; // y == 1/x mod 2^2
545 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
546 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
547 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
548 // last step - calculate inverse mod DV directly;
549 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
550 y = (y*(2-x*y%BI_DV))%BI_DV; // y == 1/x mod 2^dbits
551 // we really want the negative inverse, and -DV < y < DV
552 return (y>0)?BI_DV-y:-y;
555 // Montgomery reduction
556 function Montgomery(m) {
558 this.mp = m.invDigit();
559 this.mpl = this.mp&0x7fff;
560 this.mph = this.mp>>15;
561 this.um = (1<<(BI_DB-15))-1;
566 function montConvert(x) {
568 x.abs().dlShiftTo(this.m.t,r);
569 r.divRemTo(this.m,null,r);
570 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
575 function montRevert(x) {
582 // x = x/R mod m (HAC 14.32)
583 //var outerCounter = 0;
584 //var innerCounter = 0;
585 var globalThingy = 0;
586 function montReduce(x) {
587 var x_array = x.array;
588 while(x.t <= this.mt2) // pad x so am has enough room later
592 for(var i = 0; i < this.m.t; ++i) {
595 // faster way of calculating u0 = x[i]*mp mod DV
596 var j = x_array[i]&0x7fff;
597 var u0 = (j*this.mpl+(((j*this.mph+(x_array[i]>>15)*this.mpl)&this.um)<<15))&BI_DM;
598 // use am to combine the multiply-shift-add into one call
600 x_array[j] += this.m.am(0,u0,x,i,0,this.m.t);
602 while(x_array[j] >= BI_DV) { x_array[j] -= BI_DV; x_array[++j]++; }
605 x.drShiftTo(this.m.t,x);
606 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
609 // r = "x^2/R mod m"; x != r
610 function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
612 // r = "xy/R mod m"; x,y != r
613 function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
615 Montgomery.prototype.convert = montConvert;
616 Montgomery.prototype.revert = montRevert;
617 Montgomery.prototype.reduce = montReduce;
618 Montgomery.prototype.mulTo = montMulTo;
619 Montgomery.prototype.sqrTo = montSqrTo;
621 // (protected) true iff this is even
622 function bnpIsEven() {
623 var this_array = this.array;
624 return ((this.t>0)?(this_array[0]&1):this.s) == 0;
627 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
628 function bnpExp(e,z) {
629 if(e > 0xffffffff || e < 1) return BigInteger.ONE;
630 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
634 if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
635 else { var t = r; r = r2; r2 = t; }
640 // (public) this^e % m, 0 <= e < 2^32
641 function bnModPowInt(e,m) {
643 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
644 return this.exp(e,z);
648 BigInteger.prototype.copyTo = bnpCopyTo;
649 BigInteger.prototype.fromInt = bnpFromInt;
650 BigInteger.prototype.fromString = bnpFromString;
651 BigInteger.prototype.clamp = bnpClamp;
652 BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
653 BigInteger.prototype.drShiftTo = bnpDRShiftTo;
654 BigInteger.prototype.lShiftTo = bnpLShiftTo;
655 BigInteger.prototype.rShiftTo = bnpRShiftTo;
656 BigInteger.prototype.subTo = bnpSubTo;
657 BigInteger.prototype.multiplyTo = bnpMultiplyTo;
658 BigInteger.prototype.squareTo = bnpSquareTo;
659 BigInteger.prototype.divRemTo = bnpDivRemTo;
660 BigInteger.prototype.invDigit = bnpInvDigit;
661 BigInteger.prototype.isEven = bnpIsEven;
662 BigInteger.prototype.exp = bnpExp;
665 BigInteger.prototype.toString = bnToString;
666 BigInteger.prototype.negate = bnNegate;
667 BigInteger.prototype.abs = bnAbs;
668 BigInteger.prototype.compareTo = bnCompareTo;
669 BigInteger.prototype.bitLength = bnBitLength;
670 BigInteger.prototype.mod = bnMod;
671 BigInteger.prototype.modPowInt = bnModPowInt;
674 BigInteger.ZERO = nbv(0);
675 BigInteger.ONE = nbv(1);
676 // Copyright (c) 2005 Tom Wu
677 // All Rights Reserved.
678 // See "LICENSE" for details.
680 // Extended JavaScript BN functions, required for RSA private ops.
683 function bnClone() { var r = nbi(); this.copyTo(r); return r; }
685 // (public) return value as integer
686 function bnIntValue() {
687 var this_array = this.array;
689 if(this.t == 1) return this_array[0]-BI_DV;
690 else if(this.t == 0) return -1;
692 else if(this.t == 1) return this_array[0];
693 else if(this.t == 0) return 0;
694 // assumes 16 < DB < 32
695 return ((this_array[1]&((1<<(32-BI_DB))-1))<<BI_DB)|this_array[0];
698 // (public) return value as byte
699 function bnByteValue() {
700 var this_array = this.array;
701 return (this.t==0)?this.s:(this_array[0]<<24)>>24;
704 // (public) return value as short (assumes DB>=16)
705 function bnShortValue() {
706 var this_array = this.array;
707 return (this.t==0)?this.s:(this_array[0]<<16)>>16;
710 // (protected) return x s.t. r^x < DV
711 function bnpChunkSize(r) { return Math.floor(Math.LN2*BI_DB/Math.log(r)); }
713 // (public) 0 if this == 0, 1 if this > 0
714 function bnSigNum() {
715 var this_array = this.array;
716 if(this.s < 0) return -1;
717 else if(this.t <= 0 || (this.t == 1 && this_array[0] <= 0)) return 0;
721 // (protected) convert to radix string
722 function bnpToRadix(b) {
723 if(b == null) b = 10;
724 if(this.signum() == 0 || b < 2 || b > 36) return "0";
725 var cs = this.chunkSize(b);
726 var a = Math.pow(b,cs);
727 var d = nbv(a), y = nbi(), z = nbi(), r = "";
728 this.divRemTo(d,y,z);
729 while(y.signum() > 0) {
730 r = (a+z.intValue()).toString(b).substr(1) + r;
733 return z.intValue().toString(b) + r;
736 // (protected) convert from radix string
737 function bnpFromRadix(s,b) {
739 if(b == null) b = 10;
740 var cs = this.chunkSize(b);
741 var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
742 for(var i = 0; i < s.length; ++i) {
745 if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
751 this.dAddOffset(w,0);
757 this.dMultiply(Math.pow(b,j));
758 this.dAddOffset(w,0);
760 if(mi) BigInteger.ZERO.subTo(this,this);
763 // (protected) alternate constructor
764 function bnpFromNumber(a,b,c) {
765 if("number" == typeof b) {
766 // new BigInteger(int,int,RNG)
767 if(a < 2) this.fromInt(1);
769 this.fromNumber(a,c);
770 if(!this.testBit(a-1)) // force MSB set
771 this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
772 if(this.isEven()) this.dAddOffset(1,0); // force odd
773 while(!this.isProbablePrime(b)) {
774 this.dAddOffset(2,0);
775 if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
780 // new BigInteger(int,RNG)
781 var x = new Array(), t = a&7;
784 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
785 this.fromString(x,256);
789 // (public) convert to bigendian byte array
790 function bnToByteArray() {
791 var this_array = this.array;
792 var i = this.t, r = new Array();
794 var p = BI_DB-(i*BI_DB)%8, d, k = 0;
796 if(p < BI_DB && (d = this_array[i]>>p) != (this.s&BI_DM)>>p)
797 r[k++] = d|(this.s<<(BI_DB-p));
800 d = (this_array[i]&((1<<p)-1))<<(8-p);
801 d |= this_array[--i]>>(p+=BI_DB-8);
804 d = (this_array[i]>>(p-=8))&0xff;
805 if(p <= 0) { p += BI_DB; --i; }
807 if((d&0x80) != 0) d |= -256;
808 if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
809 if(k > 0 || d != this.s) r[k++] = d;
815 function bnEquals(a) { return(this.compareTo(a)==0); }
816 function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
817 function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
819 // (protected) r = this op a (bitwise)
820 function bnpBitwiseTo(a,op,r) {
821 var this_array = this.array;
822 var a_array = a.array;
823 var r_array = r.array;
824 var i, f, m = Math.min(a.t,this.t);
825 for(i = 0; i < m; ++i) r_array[i] = op(this_array[i],a_array[i]);
828 for(i = m; i < this.t; ++i) r_array[i] = op(this_array[i],f);
833 for(i = m; i < a.t; ++i) r_array[i] = op(f,a_array[i]);
836 r.s = op(this.s,a.s);
841 function op_and(x,y) { return x&y; }
842 function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
845 function op_or(x,y) { return x|y; }
846 function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
849 function op_xor(x,y) { return x^y; }
850 function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
852 // (public) this & ~a
853 function op_andnot(x,y) { return x&~y; }
854 function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
858 var this_array = this.array;
860 var r_array = r.array;
862 for(var i = 0; i < this.t; ++i) r_array[i] = BI_DM&~this_array[i];
868 // (public) this << n
869 function bnShiftLeft(n) {
871 if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
875 // (public) this >> n
876 function bnShiftRight(n) {
878 if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
882 // return index of lowest 1-bit in x, x < 2^31
884 if(x == 0) return -1;
886 if((x&0xffff) == 0) { x >>= 16; r += 16; }
887 if((x&0xff) == 0) { x >>= 8; r += 8; }
888 if((x&0xf) == 0) { x >>= 4; r += 4; }
889 if((x&3) == 0) { x >>= 2; r += 2; }
894 // (public) returns index of lowest 1-bit (or -1 if none)
895 function bnGetLowestSetBit() {
896 var this_array = this.array;
897 for(var i = 0; i < this.t; ++i)
898 if(this_array[i] != 0) return i*BI_DB+lbit(this_array[i]);
899 if(this.s < 0) return this.t*BI_DB;
903 // return number of 1 bits in x
906 while(x != 0) { x &= x-1; ++r; }
910 // (public) return number of set bits
911 function bnBitCount() {
912 var r = 0, x = this.s&BI_DM;
913 for(var i = 0; i < this.t; ++i) r += cbit(this_array[i]^x);
917 // (public) true iff nth bit is set
918 function bnTestBit(n) {
919 var this_array = this.array;
920 var j = Math.floor(n/BI_DB);
921 if(j >= this.t) return(this.s!=0);
922 return((this_array[j]&(1<<(n%BI_DB)))!=0);
925 // (protected) this op (1<<n)
926 function bnpChangeBit(n,op) {
927 var r = BigInteger.ONE.shiftLeft(n);
928 this.bitwiseTo(r,op,r);
932 // (public) this | (1<<n)
933 function bnSetBit(n) { return this.changeBit(n,op_or); }
935 // (public) this & ~(1<<n)
936 function bnClearBit(n) { return this.changeBit(n,op_andnot); }
938 // (public) this ^ (1<<n)
939 function bnFlipBit(n) { return this.changeBit(n,op_xor); }
941 // (protected) r = this + a
942 function bnpAddTo(a,r) {
943 var this_array = this.array;
944 var a_array = a.array;
945 var r_array = r.array;
946 var i = 0, c = 0, m = Math.min(a.t,this.t);
948 c += this_array[i]+a_array[i];
949 r_array[i++] = c&BI_DM;
956 r_array[i++] = c&BI_DM;
965 r_array[i++] = c&BI_DM;
971 if(c > 0) r_array[i++] = c;
972 else if(c < -1) r_array[i++] = BI_DV+c;
978 function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
981 function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
984 function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
987 function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
990 function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
992 // (public) [this/a,this%a]
993 function bnDivideAndRemainder(a) {
994 var q = nbi(), r = nbi();
995 this.divRemTo(a,q,r);
996 return new Array(q,r);
999 // (protected) this *= n, this >= 0, 1 < n < DV
1000 function bnpDMultiply(n) {
1001 var this_array = this.array;
1002 this_array[this.t] = this.am(0,n-1,this,0,0,this.t);
1007 // (protected) this += n << w words, this >= 0
1008 function bnpDAddOffset(n,w) {
1009 var this_array = this.array;
1010 while(this.t <= w) this_array[this.t++] = 0;
1012 while(this_array[w] >= BI_DV) {
1013 this_array[w] -= BI_DV;
1014 if(++w >= this.t) this_array[this.t++] = 0;
1020 function NullExp() {}
1021 function nNop(x) { return x; }
1022 function nMulTo(x,y,r) { x.multiplyTo(y,r); }
1023 function nSqrTo(x,r) { x.squareTo(r); }
1025 NullExp.prototype.convert = nNop;
1026 NullExp.prototype.revert = nNop;
1027 NullExp.prototype.mulTo = nMulTo;
1028 NullExp.prototype.sqrTo = nSqrTo;
1031 function bnPow(e) { return this.exp(e,new NullExp()); }
1033 // (protected) r = lower n words of "this * a", a.t <= n
1034 // "this" should be the larger one if appropriate.
1035 function bnpMultiplyLowerTo(a,n,r) {
1036 var r_array = r.array;
1037 var a_array = a.array;
1038 var i = Math.min(this.t+a.t,n);
1039 r.s = 0; // assumes a,this >= 0
1041 while(i > 0) r_array[--i] = 0;
1043 for(j = r.t-this.t; i < j; ++i) r_array[i+this.t] = this.am(0,a_array[i],r,i,0,this.t);
1044 for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a_array[i],r,i,0,n-i);
1048 // (protected) r = "this * a" without lower n words, n > 0
1049 // "this" should be the larger one if appropriate.
1050 function bnpMultiplyUpperTo(a,n,r) {
1051 var r_array = r.array;
1052 var a_array = a.array;
1054 var i = r.t = this.t+a.t-n;
1055 r.s = 0; // assumes a,this >= 0
1056 while(--i >= 0) r_array[i] = 0;
1057 for(i = Math.max(n-this.t,0); i < a.t; ++i)
1058 r_array[this.t+i-n] = this.am(n-i,a_array[i],r,0,0,this.t+i-n);
1063 // Barrett modular reduction
1064 function Barrett(m) {
1068 BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
1069 this.mu = this.r2.divide(m);
1073 function barrettConvert(x) {
1074 if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
1075 else if(x.compareTo(this.m) < 0) return x;
1076 else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
1079 function barrettRevert(x) { return x; }
1081 // x = x mod m (HAC 14.42)
1082 function barrettReduce(x) {
1083 x.drShiftTo(this.m.t-1,this.r2);
1084 if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
1085 this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
1086 this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
1087 while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
1089 while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
1092 // r = x^2 mod m; x != r
1093 function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
1095 // r = x*y mod m; x,y != r
1096 function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
1098 Barrett.prototype.convert = barrettConvert;
1099 Barrett.prototype.revert = barrettRevert;
1100 Barrett.prototype.reduce = barrettReduce;
1101 Barrett.prototype.mulTo = barrettMulTo;
1102 Barrett.prototype.sqrTo = barrettSqrTo;
1104 // (public) this^e % m (HAC 14.85)
1105 function bnModPow(e,m) {
1106 var e_array = e.array;
1107 var i = e.bitLength(), k, r = nbv(1), z;
1108 if(i <= 0) return r;
1109 else if(i < 18) k = 1;
1110 else if(i < 48) k = 3;
1111 else if(i < 144) k = 4;
1112 else if(i < 768) k = 5;
1119 z = new Montgomery(m);
1122 var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
1123 g[1] = z.convert(this);
1129 z.mulTo(g2,g[n-2],g[n]);
1134 var j = e.t-1, w, is1 = true, r2 = nbi(), t;
1135 i = nbits(e_array[j])-1;
1137 if(i >= k1) w = (e_array[j]>>(i-k1))&km;
1139 w = (e_array[j]&((1<<(i+1))-1))<<(k1-i);
1140 if(j > 0) w |= e_array[j-1]>>(BI_DB+i-k1);
1144 while((w&1) == 0) { w >>= 1; --n; }
1145 if((i -= n) < 0) { i += BI_DB; --j; }
1146 if(is1) { // ret == 1, don't bother squaring or multiplying it
1151 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
1152 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
1156 while(j >= 0 && (e_array[j]&(1<<i)) == 0) {
1157 z.sqrTo(r,r2); t = r; r = r2; r2 = t;
1158 if(--i < 0) { i = BI_DB-1; --j; }
1164 // (public) gcd(this,a) (HAC 14.54)
1166 var x = (this.s<0)?this.negate():this.clone();
1167 var y = (a.s<0)?a.negate():a.clone();
1168 if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
1169 var i = x.getLowestSetBit(), g = y.getLowestSetBit();
1176 while(x.signum() > 0) {
1177 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
1178 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
1179 if(x.compareTo(y) >= 0) {
1188 if(g > 0) y.lShiftTo(g,y);
1192 // (protected) this % n, n < 2^26
1193 function bnpModInt(n) {
1194 var this_array = this.array;
1195 if(n <= 0) return 0;
1196 var d = BI_DV%n, r = (this.s<0)?n-1:0;
1198 if(d == 0) r = this_array[0]%n;
1199 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this_array[i])%n;
1203 // (public) 1/this % m (HAC 14.61)
1204 function bnModInverse(m) {
1205 var ac = m.isEven();
1206 if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
1207 var u = m.clone(), v = this.clone();
1208 var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
1209 while(u.signum() != 0) {
1213 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
1216 else if(!b.isEven()) b.subTo(m,b);
1222 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
1225 else if(!d.isEven()) d.subTo(m,d);
1228 if(u.compareTo(v) >= 0) {
1230 if(ac) a.subTo(c,a);
1235 if(ac) c.subTo(a,c);
1239 if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
1240 if(d.compareTo(m) >= 0) return d.subtract(m);
1241 if(d.signum() < 0) d.addTo(m,d); else return d;
1242 if(d.signum() < 0) return d.add(m); else return d;
1245 var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];
1246 var lplim = (1<<26)/lowprimes[lowprimes.length-1];
1248 // (public) test primality with certainty >= 1-.5^t
1249 function bnIsProbablePrime(t) {
1250 var i, x = this.abs();
1251 var x_array = x.array;
1252 if(x.t == 1 && x_array[0] <= lowprimes[lowprimes.length-1]) {
1253 for(i = 0; i < lowprimes.length; ++i)
1254 if(x_array[0] == lowprimes[i]) return true;
1257 if(x.isEven()) return false;
1259 while(i < lowprimes.length) {
1260 var m = lowprimes[i], j = i+1;
1261 while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
1263 while(i < j) if(m%lowprimes[i++] == 0) return false;
1265 return x.millerRabin(t);
1268 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
1269 function bnpMillerRabin(t) {
1270 var n1 = this.subtract(BigInteger.ONE);
1271 var k = n1.getLowestSetBit();
1272 if(k <= 0) return false;
1273 var r = n1.shiftRight(k);
1275 if(t > lowprimes.length) t = lowprimes.length;
1277 for(var i = 0; i < t; ++i) {
1278 a.fromInt(lowprimes[i]);
1279 var y = a.modPow(r,this);
1280 if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
1282 while(j++ < k && y.compareTo(n1) != 0) {
1283 y = y.modPowInt(2,this);
1284 if(y.compareTo(BigInteger.ONE) == 0) return false;
1286 if(y.compareTo(n1) != 0) return false;
1293 BigInteger.prototype.chunkSize = bnpChunkSize;
1294 BigInteger.prototype.toRadix = bnpToRadix;
1295 BigInteger.prototype.fromRadix = bnpFromRadix;
1296 BigInteger.prototype.fromNumber = bnpFromNumber;
1297 BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
1298 BigInteger.prototype.changeBit = bnpChangeBit;
1299 BigInteger.prototype.addTo = bnpAddTo;
1300 BigInteger.prototype.dMultiply = bnpDMultiply;
1301 BigInteger.prototype.dAddOffset = bnpDAddOffset;
1302 BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
1303 BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
1304 BigInteger.prototype.modInt = bnpModInt;
1305 BigInteger.prototype.millerRabin = bnpMillerRabin;
1308 BigInteger.prototype.clone = bnClone;
1309 BigInteger.prototype.intValue = bnIntValue;
1310 BigInteger.prototype.byteValue = bnByteValue;
1311 BigInteger.prototype.shortValue = bnShortValue;
1312 BigInteger.prototype.signum = bnSigNum;
1313 BigInteger.prototype.toByteArray = bnToByteArray;
1314 BigInteger.prototype.equals = bnEquals;
1315 BigInteger.prototype.min = bnMin;
1316 BigInteger.prototype.max = bnMax;
1317 BigInteger.prototype.and = bnAnd;
1318 BigInteger.prototype.or = bnOr;
1319 BigInteger.prototype.xor = bnXor;
1320 BigInteger.prototype.andNot = bnAndNot;
1321 BigInteger.prototype.not = bnNot;
1322 BigInteger.prototype.shiftLeft = bnShiftLeft;
1323 BigInteger.prototype.shiftRight = bnShiftRight;
1324 BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
1325 BigInteger.prototype.bitCount = bnBitCount;
1326 BigInteger.prototype.testBit = bnTestBit;
1327 BigInteger.prototype.setBit = bnSetBit;
1328 BigInteger.prototype.clearBit = bnClearBit;
1329 BigInteger.prototype.flipBit = bnFlipBit;
1330 BigInteger.prototype.add = bnAdd;
1331 BigInteger.prototype.subtract = bnSubtract;
1332 BigInteger.prototype.multiply = bnMultiply;
1333 BigInteger.prototype.divide = bnDivide;
1334 BigInteger.prototype.remainder = bnRemainder;
1335 BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
1336 BigInteger.prototype.modPow = bnModPow;
1337 BigInteger.prototype.modInverse = bnModInverse;
1338 BigInteger.prototype.pow = bnPow;
1339 BigInteger.prototype.gcd = bnGCD;
1340 BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
1342 // BigInteger interfaces not implemented in jsbn:
1344 // BigInteger(int signum, byte[] magnitude)
1345 // double doubleValue()
1346 // float floatValue()
1349 // static BigInteger valueOf(long val)
1350 // prng4.js - uses Arcfour as a PRNG
1352 function Arcfour() {
1355 this.S = new Array();
1358 // Initialize arcfour context from key, an array of ints, each from [0..255]
1359 function ARC4init(key) {
1361 for(i = 0; i < 256; ++i)
1364 for(i = 0; i < 256; ++i) {
1365 j = (j + this.S[i] + key[i % key.length]) & 255;
1367 this.S[i] = this.S[j];
1374 function ARC4next() {
1376 this.i = (this.i + 1) & 255;
1377 this.j = (this.j + this.S[this.i]) & 255;
1379 this.S[this.i] = this.S[this.j];
1381 return this.S[(t + this.S[this.i]) & 255];
1384 Arcfour.prototype.init = ARC4init;
1385 Arcfour.prototype.next = ARC4next;
1387 // Plug in your RNG constructor here
1388 function prng_newstate() {
1389 return new Arcfour();
1392 // Pool size must be a multiple of 4 and greater than 32.
1393 // An array of bytes the size of the pool will be passed to init()
1394 var rng_psize = 256;
1395 // Random number generator - requires a PRNG backend, e.g. prng4.js
1397 // For best results, put code like
1398 // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
1399 // in your main HTML document.
1405 // Mix in a 32-bit integer into the pool
1406 function rng_seed_int(x) {
1407 rng_pool[rng_pptr++] ^= x & 255;
1408 rng_pool[rng_pptr++] ^= (x >> 8) & 255;
1409 rng_pool[rng_pptr++] ^= (x >> 16) & 255;
1410 rng_pool[rng_pptr++] ^= (x >> 24) & 255;
1411 if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
1414 // Mix in the current time (w/milliseconds) into the pool
1415 function rng_seed_time() {
1416 // Use pre-computed date to avoid making the benchmark
1417 // results dependent on the current date.
1418 rng_seed_int(1122926989487);
1421 // Initialize the pool with junk if needed.
1422 if(rng_pool == null) {
1423 rng_pool = new Array();
1426 while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
1427 t = Math.floor(65536 * Math.random());
1428 rng_pool[rng_pptr++] = t >>> 8;
1429 rng_pool[rng_pptr++] = t & 255;
1433 //rng_seed_int(window.screenX);
1434 //rng_seed_int(window.screenY);
1437 function rng_get_byte() {
1438 if(rng_state == null) {
1440 rng_state = prng_newstate();
1441 rng_state.init(rng_pool);
1442 for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
1443 rng_pool[rng_pptr] = 0;
1447 // TODO: allow reseeding after first request
1448 return rng_state.next();
1451 function rng_get_bytes(ba) {
1453 for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
1456 function SecureRandom() {}
1458 SecureRandom.prototype.nextBytes = rng_get_bytes;
1459 // Depends on jsbn.js and rng.js
1461 // convert a (hex) string to a bignum object
1462 function parseBigInt(str,r) {
1463 return new BigInteger(str,r);
1466 function linebrk(s,n) {
1469 while(i + n < s.length) {
1470 ret += s.substring(i,i+n) + "\n";
1473 return ret + s.substring(i,s.length);
1476 function byte2Hex(b) {
1478 return "0" + b.toString(16);
1480 return b.toString(16);
1483 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
1484 function pkcs1pad2(s,n) {
1485 if(n < s.length + 11) {
1486 alert("Message too long for RSA");
1489 var ba = new Array();
1490 var i = s.length - 1;
1491 while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);
1493 var rng = new SecureRandom();
1494 var x = new Array();
1495 while(n > 2) { // random non-zero pad
1497 while(x[0] == 0) rng.nextBytes(x);
1502 return new BigInteger(ba);
1505 // "empty" RSA key constructor
1517 // Set the public key fields N and e from hex strings
1518 function RSASetPublic(N,E) {
1519 if(N != null && E != null && N.length > 0 && E.length > 0) {
1520 this.n = parseBigInt(N,16);
1521 this.e = parseInt(E,16);
1524 alert("Invalid RSA public key");
1527 // Perform raw public operation on "x": return x^e (mod n)
1528 function RSADoPublic(x) {
1529 return x.modPowInt(this.e, this.n);
1532 // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
1533 function RSAEncrypt(text) {
1534 var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
1535 if(m == null) return null;
1536 var c = this.doPublic(m);
1537 if(c == null) return null;
1538 var h = c.toString(16);
1539 if((h.length & 1) == 0) return h; else return "0" + h;
1542 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
1543 //function RSAEncryptB64(text) {
1544 // var h = this.encrypt(text);
1545 // if(h) return hex2b64(h); else return null;
1549 RSAKey.prototype.doPublic = RSADoPublic;
1552 RSAKey.prototype.setPublic = RSASetPublic;
1553 RSAKey.prototype.encrypt = RSAEncrypt;
1554 //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
1555 // Depends on rsa.js and jsbn2.js
1557 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
1558 function pkcs1unpad2(d,n) {
1559 var b = d.toByteArray();
1561 while(i < b.length && b[i] == 0) ++i;
1562 if(b.length-i != n-1 || b[i] != 2)
1566 if(++i >= b.length) return null;
1568 while(++i < b.length)
1569 ret += String.fromCharCode(b[i]);
1573 // Set the private key fields N, e, and d from hex strings
1574 function RSASetPrivate(N,E,D) {
1575 if(N != null && E != null && N.length > 0 && E.length > 0) {
1576 this.n = parseBigInt(N,16);
1577 this.e = parseInt(E,16);
1578 this.d = parseBigInt(D,16);
1581 alert("Invalid RSA private key");
1584 // Set the private key fields N, e, d and CRT params from hex strings
1585 function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
1586 if(N != null && E != null && N.length > 0 && E.length > 0) {
1587 this.n = parseBigInt(N,16);
1588 this.e = parseInt(E,16);
1589 this.d = parseBigInt(D,16);
1590 this.p = parseBigInt(P,16);
1591 this.q = parseBigInt(Q,16);
1592 this.dmp1 = parseBigInt(DP,16);
1593 this.dmq1 = parseBigInt(DQ,16);
1594 this.coeff = parseBigInt(C,16);
1597 alert("Invalid RSA private key");
1600 // Generate a new random private key B bits long, using public expt E
1601 function RSAGenerate(B,E) {
1602 var rng = new SecureRandom();
1604 this.e = parseInt(E,16);
1605 var ee = new BigInteger(E,16);
1608 this.p = new BigInteger(B-qs,1,rng);
1609 if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
1612 this.q = new BigInteger(qs,1,rng);
1613 if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
1615 if(this.p.compareTo(this.q) <= 0) {
1620 var p1 = this.p.subtract(BigInteger.ONE);
1621 var q1 = this.q.subtract(BigInteger.ONE);
1622 var phi = p1.multiply(q1);
1623 if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
1624 this.n = this.p.multiply(this.q);
1625 this.d = ee.modInverse(phi);
1626 this.dmp1 = this.d.mod(p1);
1627 this.dmq1 = this.d.mod(q1);
1628 this.coeff = this.q.modInverse(this.p);
1634 // Perform raw private operation on "x": return x^d (mod n)
1635 function RSADoPrivate(x) {
1636 if(this.p == null || this.q == null)
1637 return x.modPow(this.d, this.n);
1639 // TODO: re-calculate any missing CRT params
1640 var xp = x.mod(this.p).modPow(this.dmp1, this.p);
1641 var xq = x.mod(this.q).modPow(this.dmq1, this.q);
1643 while(xp.compareTo(xq) < 0)
1644 xp = xp.add(this.p);
1645 return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
1648 // Return the PKCS#1 RSA decryption of "ctext".
1649 // "ctext" is an even-length hex string and the output is a plain string.
1650 function RSADecrypt(ctext) {
1651 var c = parseBigInt(ctext, 16);
1652 var m = this.doPrivate(c);
1653 if(m == null) return null;
1654 return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
1657 // Return the PKCS#1 RSA decryption of "ctext".
1658 // "ctext" is a Base64-encoded string and the output is a plain string.
1659 //function RSAB64Decrypt(ctext) {
1660 // var h = b64tohex(ctext);
1661 // if(h) return this.decrypt(h); else return null;
1665 RSAKey.prototype.doPrivate = RSADoPrivate;
1668 RSAKey.prototype.setPrivate = RSASetPrivate;
1669 RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
1670 RSAKey.prototype.generate = RSAGenerate;
1671 RSAKey.prototype.decrypt = RSADecrypt;
1672 //RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
1675 nValue="a5261939975948bb7a58dffe5ff54e65f0498f9175f5a09288810b8975871e99af3b5dd94057b0fc07535f5f97444504fa35169d461d0d30cf0192e307727c065168c788771c561a9400fb49175e9e6aa4e23fe11af69e9412dd23b0cb6684c4c2429bce139e848ab26d0829073351f4acd36074eafd036a5eb83359d2a698d3";
1677 dValue="8e9912f6d3645894e8d38cb58c0db81ff516cf4c7e5a14c7f1eddb1459d2cded4d8d293fc97aee6aefb861859c8b6a3d1dfe710463e1f9ddc72048c09751971c4a580aa51eb523357a3cc48d31cfad1d4a165066ed92d4748fb6571211da5cb14bc11b6e2df7c1a559e6d5ac1cd5c94703a22891464fba23d0d965086277a161";
1678 pValue="d090ce58a92c75233a6486cb0a9209bf3583b64f540c76f5294bb97d285eed33aec220bde14b2417951178ac152ceab6da7090905b478195498b352048f15e7d";
1679 qValue="cab575dc652bb66df15a0359609d51d1db184750c00c6698b90ef3465c99655103edbf0d54c56aec0ce3c4d22592338092a126a0cc49f65a4a30d222b411e58f";
1680 dmp1Value="1a24bca8e273df2f0e47c199bbf678604e7df7215480c77c8db39f49b000ce2cf7500038acfff5433b7d582a01f1826e6f4d42e1c57f5e1fef7b12aabc59fd25";
1681 dmq1Value="3d06982efbbe47339e1f6d36b1216b8a741d410b0c662f54f7118b27b9a4ec9d914337eb39841d8666f3034408cf94f5b62f11c402fc994fe15a05493150d9fd";
1682 coeffValue="3a3e731acd8960b7ff9eb81a7ff93bd1cfa74cbd56987db58b4594fb09c09084db1734c8143f98b602b981aaa9243ca28deb69b5b280ee8dcee0fd2625e53250";
1684 setupEngine(am3, 28);
1686 var TEXT = "The quick brown fox jumped over the extremely lazy frog! " +
1687 "Now is the time for all good men to come to the party.";
1690 function encrypt() {
1691 var RSA = new RSAKey();
1692 RSA.setPublic(nValue, eValue);
1693 RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue);
1694 encrypted = RSA.encrypt(TEXT);
1697 function decrypt() {
1698 var RSA = new RSAKey();
1699 RSA.setPublic(nValue, eValue);
1700 RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue);
1701 var decrypted = RSA.decrypt(encrypted);
1702 if (decrypted != TEXT) {
1703 throw new Error("Crypto operation failed");