[Service] Upgrade device home as v1.0.4
[platform/framework/web/wrtjs.git] / device_home / service / jsencrypt.js
1 (function (global, factory) {
2         typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3         typeof define === 'function' && define.amd ? define(['exports'], factory) :
4         (factory((global.JSEncrypt = {})));
5 }(this, (function (exports) { 'use strict';
6
7 const crypto = require('crypto');
8 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
9
10 Math.random = function() {
11     const byteArray = new Uint32Array(1);
12     return (crypto.getRandomValues(byteArray))[0];
13 }
14
15 function int2char(n) {
16     return BI_RM.charAt(n);
17 }
18 //#region BIT_OPERATIONS
19 // (public) this & a
20 function op_and(x, y) {
21     return x & y;
22 }
23 // (public) this | a
24 function op_or(x, y) {
25     return x | y;
26 }
27 // (public) this ^ a
28 function op_xor(x, y) {
29     return x ^ y;
30 }
31 // (public) this & ~a
32 function op_andnot(x, y) {
33     return x & ~y;
34 }
35 // return index of lowest 1-bit in x, x < 2^31
36 function lbit(x) {
37     if (x == 0) {
38         return -1;
39     }
40     var r = 0;
41     if ((x & 0xffff) == 0) {
42         x >>= 16;
43         r += 16;
44     }
45     if ((x & 0xff) == 0) {
46         x >>= 8;
47         r += 8;
48     }
49     if ((x & 0xf) == 0) {
50         x >>= 4;
51         r += 4;
52     }
53     if ((x & 3) == 0) {
54         x >>= 2;
55         r += 2;
56     }
57     if ((x & 1) == 0) {
58         ++r;
59     }
60     return r;
61 }
62 // return number of 1 bits in x
63 function cbit(x) {
64     var r = 0;
65     while (x != 0) {
66         x &= x - 1;
67         ++r;
68     }
69     return r;
70 }
71 //#endregion BIT_OPERATIONS
72
73 var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
74 var b64pad = "=";
75 function hex2b64(h) {
76     var i;
77     var c;
78     var ret = "";
79     for (i = 0; i + 3 <= h.length; i += 3) {
80         c = parseInt(h.substring(i, i + 3), 16);
81         ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
82     }
83     if (i + 1 == h.length) {
84         c = parseInt(h.substring(i, i + 1), 16);
85         ret += b64map.charAt(c << 2);
86     }
87     else if (i + 2 == h.length) {
88         c = parseInt(h.substring(i, i + 2), 16);
89         ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
90     }
91     while ((ret.length & 3) > 0) {
92         ret += b64pad;
93     }
94     return ret;
95 }
96 // convert a base64 string to hex
97 function b64tohex(s) {
98     var ret = "";
99     var i;
100     var k = 0; // b64 state, 0-3
101     var slop = 0;
102     for (i = 0; i < s.length; ++i) {
103         if (s.charAt(i) == b64pad) {
104             break;
105         }
106         var v = b64map.indexOf(s.charAt(i));
107         if (v < 0) {
108             continue;
109         }
110         if (k == 0) {
111             ret += int2char(v >> 2);
112             slop = v & 3;
113             k = 1;
114         }
115         else if (k == 1) {
116             ret += int2char((slop << 2) | (v >> 4));
117             slop = v & 0xf;
118             k = 2;
119         }
120         else if (k == 2) {
121             ret += int2char(slop);
122             ret += int2char(v >> 2);
123             slop = v & 3;
124             k = 3;
125         }
126         else {
127             ret += int2char((slop << 2) | (v >> 4));
128             ret += int2char(v & 0xf);
129             k = 0;
130         }
131     }
132     if (k == 1) {
133         ret += int2char(slop << 2);
134     }
135     return ret;
136 }
137
138 /*! *****************************************************************************
139 Copyright (c) Microsoft Corporation. All rights reserved.
140 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
141 this file except in compliance with the License. You may obtain a copy of the
142 License at http://www.apache.org/licenses/LICENSE-2.0
143 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
144 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
145 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
146 MERCHANTABLITY OR NON-INFRINGEMENT.
147 See the Apache Version 2.0 License for specific language governing permissions
148 and limitations under the License.
149 ***************************************************************************** */
150 /* global Reflect, Promise */
151
152 var extendStatics = function(d, b) {
153     extendStatics = Object.setPrototypeOf ||
154         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
155         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
156     return extendStatics(d, b);
157 };
158
159 function __extends(d, b) {
160     extendStatics(d, b);
161     function __() { this.constructor = d; }
162     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
163 }
164
165 // Hex JavaScript decoder
166 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
167 // Permission to use, copy, modify, and/or distribute this software for any
168 // purpose with or without fee is hereby granted, provided that the above
169 // copyright notice and this permission notice appear in all copies.
170 //
171 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
172 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
173 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
174 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
175 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
176 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
177 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
178 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
179 var decoder;
180 var Hex = {
181     decode: function (a) {
182         var i;
183         if (decoder === undefined) {
184             var hex = "0123456789ABCDEF";
185             var ignore = " \f\n\r\t\u00A0\u2028\u2029";
186             decoder = {};
187             for (i = 0; i < 16; ++i) {
188                 decoder[hex.charAt(i)] = i;
189             }
190             hex = hex.toLowerCase();
191             for (i = 10; i < 16; ++i) {
192                 decoder[hex.charAt(i)] = i;
193             }
194             for (i = 0; i < ignore.length; ++i) {
195                 decoder[ignore.charAt(i)] = -1;
196             }
197         }
198         var out = [];
199         var bits = 0;
200         var char_count = 0;
201         for (i = 0; i < a.length; ++i) {
202             var c = a.charAt(i);
203             if (c == "=") {
204                 break;
205             }
206             c = decoder[c];
207             if (c == -1) {
208                 continue;
209             }
210             if (c === undefined) {
211                 throw new Error("Illegal character at offset " + i);
212             }
213             bits |= c;
214             if (++char_count >= 2) {
215                 out[out.length] = bits;
216                 bits = 0;
217                 char_count = 0;
218             }
219             else {
220                 bits <<= 4;
221             }
222         }
223         if (char_count) {
224             throw new Error("Hex encoding incomplete: 4 bits missing");
225         }
226         return out;
227     }
228 };
229
230 // Base64 JavaScript decoder
231 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
232 // Permission to use, copy, modify, and/or distribute this software for any
233 // purpose with or without fee is hereby granted, provided that the above
234 // copyright notice and this permission notice appear in all copies.
235 //
236 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
237 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
238 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
239 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
240 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
241 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
242 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
243 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
244 var decoder$1;
245 var Base64 = {
246     decode: function (a) {
247         var i;
248         if (decoder$1 === undefined) {
249             var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
250             var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
251             decoder$1 = Object.create(null);
252             for (i = 0; i < 64; ++i) {
253                 decoder$1[b64.charAt(i)] = i;
254             }
255             for (i = 0; i < ignore.length; ++i) {
256                 decoder$1[ignore.charAt(i)] = -1;
257             }
258         }
259         var out = [];
260         var bits = 0;
261         var char_count = 0;
262         for (i = 0; i < a.length; ++i) {
263             var c = a.charAt(i);
264             if (c == "=") {
265                 break;
266             }
267             c = decoder$1[c];
268             if (c == -1) {
269                 continue;
270             }
271             if (c === undefined) {
272                 throw new Error("Illegal character at offset " + i);
273             }
274             bits |= c;
275             if (++char_count >= 4) {
276                 out[out.length] = (bits >> 16);
277                 out[out.length] = (bits >> 8) & 0xFF;
278                 out[out.length] = bits & 0xFF;
279                 bits = 0;
280                 char_count = 0;
281             }
282             else {
283                 bits <<= 6;
284             }
285         }
286         switch (char_count) {
287             case 1:
288                 throw new Error("Base64 encoding incomplete: at least 2 bits missing");
289             case 2:
290                 out[out.length] = (bits >> 10);
291                 break;
292             case 3:
293                 out[out.length] = (bits >> 16);
294                 out[out.length] = (bits >> 8) & 0xFF;
295                 break;
296         }
297         return out;
298     },
299     re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
300     unarmor: function (a) {
301         var m = Base64.re.exec(a);
302         if (m) {
303             if (m[1]) {
304                 a = m[1];
305             }
306             else if (m[2]) {
307                 a = m[2];
308             }
309             else {
310                 throw new Error("RegExp out of sync");
311             }
312         }
313         return Base64.decode(a);
314     }
315 };
316
317 // Big integer base-10 printing library
318 // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
319 // Permission to use, copy, modify, and/or distribute this software for any
320 // purpose with or without fee is hereby granted, provided that the above
321 // copyright notice and this permission notice appear in all copies.
322 //
323 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
324 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
325 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
326 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
327 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
328 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
329 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
330 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
331 var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
332 var Int10 = /** @class */ (function () {
333     function Int10(value) {
334         this.buf = [+value || 0];
335     }
336     Int10.prototype.mulAdd = function (m, c) {
337         // assert(m <= 256)
338         var b = this.buf;
339         var l = b.length;
340         var i;
341         var t;
342         for (i = 0; i < l; ++i) {
343             t = b[i] * m + c;
344             if (t < max) {
345                 c = 0;
346             }
347             else {
348                 c = 0 | (t / max);
349                 t -= c * max;
350             }
351             b[i] = t;
352         }
353         if (c > 0) {
354             b[i] = c;
355         }
356     };
357     Int10.prototype.sub = function (c) {
358         // assert(m <= 256)
359         var b = this.buf;
360         var l = b.length;
361         var i;
362         var t;
363         for (i = 0; i < l; ++i) {
364             t = b[i] - c;
365             if (t < 0) {
366                 t += max;
367                 c = 1;
368             }
369             else {
370                 c = 0;
371             }
372             b[i] = t;
373         }
374         while (b[b.length - 1] === 0) {
375             b.pop();
376         }
377     };
378     Int10.prototype.toString = function (base) {
379         if ((base || 10) != 10) {
380             throw new Error("only base 10 is supported");
381         }
382         var b = this.buf;
383         var s = b[b.length - 1].toString();
384         for (var i = b.length - 2; i >= 0; --i) {
385             s += (max + b[i]).toString().substring(1);
386         }
387         return s;
388     };
389     Int10.prototype.valueOf = function () {
390         var b = this.buf;
391         var v = 0;
392         for (var i = b.length - 1; i >= 0; --i) {
393             v = v * max + b[i];
394         }
395         return v;
396     };
397     Int10.prototype.simplify = function () {
398         var b = this.buf;
399         return (b.length == 1) ? b[0] : this;
400     };
401     return Int10;
402 }());
403
404 // ASN.1 JavaScript decoder
405 var ellipsis = "\u2026";
406 var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
407 var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
408 function stringCut(str, len) {
409     if (str.length > len) {
410         str = str.substring(0, len) + ellipsis;
411     }
412     return str;
413 }
414 var Stream = /** @class */ (function () {
415     function Stream(enc, pos) {
416         this.hexDigits = "0123456789ABCDEF";
417         if (enc instanceof Stream) {
418             this.enc = enc.enc;
419             this.pos = enc.pos;
420         }
421         else {
422             // enc should be an array or a binary string
423             this.enc = enc;
424             this.pos = pos;
425         }
426     }
427     Stream.prototype.get = function (pos) {
428         if (pos === undefined) {
429             pos = this.pos++;
430         }
431         if (pos >= this.enc.length) {
432             throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
433         }
434         return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
435     };
436     Stream.prototype.hexByte = function (b) {
437         return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
438     };
439     Stream.prototype.hexDump = function (start, end, raw) {
440         var s = "";
441         for (var i = start; i < end; ++i) {
442             s += this.hexByte(this.get(i));
443             if (raw !== true) {
444                 switch (i & 0xF) {
445                     case 0x7:
446                         s += "  ";
447                         break;
448                     case 0xF:
449                         s += "\n";
450                         break;
451                     default:
452                         s += " ";
453                 }
454             }
455         }
456         return s;
457     };
458     Stream.prototype.isASCII = function (start, end) {
459         for (var i = start; i < end; ++i) {
460             var c = this.get(i);
461             if (c < 32 || c > 176) {
462                 return false;
463             }
464         }
465         return true;
466     };
467     Stream.prototype.parseStringISO = function (start, end) {
468         var s = "";
469         for (var i = start; i < end; ++i) {
470             s += String.fromCharCode(this.get(i));
471         }
472         return s;
473     };
474     Stream.prototype.parseStringUTF = function (start, end) {
475         var s = "";
476         for (var i = start; i < end;) {
477             var c = this.get(i++);
478             if (c < 128) {
479                 s += String.fromCharCode(c);
480             }
481             else if ((c > 191) && (c < 224)) {
482                 s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
483             }
484             else {
485                 s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
486             }
487         }
488         return s;
489     };
490     Stream.prototype.parseStringBMP = function (start, end) {
491         var str = "";
492         var hi;
493         var lo;
494         for (var i = start; i < end;) {
495             hi = this.get(i++);
496             lo = this.get(i++);
497             str += String.fromCharCode((hi << 8) | lo);
498         }
499         return str;
500     };
501     Stream.prototype.parseTime = function (start, end, shortYear) {
502         var s = this.parseStringISO(start, end);
503         var m = (shortYear ? reTimeS : reTimeL).exec(s);
504         if (!m) {
505             return "Unrecognized time: " + s;
506         }
507         if (shortYear) {
508             // to avoid querying the timer, use the fixed range [1970, 2069]
509             // it will conform with ITU X.400 [-10, +40] sliding window until 2030
510             m[1] = +m[1];
511             m[1] += (+m[1] < 70) ? 2000 : 1900;
512         }
513         s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
514         if (m[5]) {
515             s += ":" + m[5];
516             if (m[6]) {
517                 s += ":" + m[6];
518                 if (m[7]) {
519                     s += "." + m[7];
520                 }
521             }
522         }
523         if (m[8]) {
524             s += " UTC";
525             if (m[8] != "Z") {
526                 s += m[8];
527                 if (m[9]) {
528                     s += ":" + m[9];
529                 }
530             }
531         }
532         return s;
533     };
534     Stream.prototype.parseInteger = function (start, end) {
535         var v = this.get(start);
536         var neg = (v > 127);
537         var pad = neg ? 255 : 0;
538         var len;
539         var s = "";
540         // skip unuseful bits (not allowed in DER)
541         while (v == pad && ++start < end) {
542             v = this.get(start);
543         }
544         len = end - start;
545         if (len === 0) {
546             return neg ? -1 : 0;
547         }
548         // show bit length of huge integers
549         if (len > 4) {
550             s = v;
551             len <<= 3;
552             while (((+s ^ pad) & 0x80) == 0) {
553                 s = +s << 1;
554                 --len;
555             }
556             s = "(" + len + " bit)\n";
557         }
558         // decode the integer
559         if (neg) {
560             v = v - 256;
561         }
562         var n = new Int10(v);
563         for (var i = start + 1; i < end; ++i) {
564             n.mulAdd(256, this.get(i));
565         }
566         return s + n.toString();
567     };
568     Stream.prototype.parseBitString = function (start, end, maxLength) {
569         var unusedBit = this.get(start);
570         var lenBit = ((end - start - 1) << 3) - unusedBit;
571         var intro = "(" + lenBit + " bit)\n";
572         var s = "";
573         for (var i = start + 1; i < end; ++i) {
574             var b = this.get(i);
575             var skip = (i == end - 1) ? unusedBit : 0;
576             for (var j = 7; j >= skip; --j) {
577                 s += (b >> j) & 1 ? "1" : "0";
578             }
579             if (s.length > maxLength) {
580                 return intro + stringCut(s, maxLength);
581             }
582         }
583         return intro + s;
584     };
585     Stream.prototype.parseOctetString = function (start, end, maxLength) {
586         if (this.isASCII(start, end)) {
587             return stringCut(this.parseStringISO(start, end), maxLength);
588         }
589         var len = end - start;
590         var s = "(" + len + " byte)\n";
591         maxLength /= 2; // we work in bytes
592         if (len > maxLength) {
593             end = start + maxLength;
594         }
595         for (var i = start; i < end; ++i) {
596             s += this.hexByte(this.get(i));
597         }
598         if (len > maxLength) {
599             s += ellipsis;
600         }
601         return s;
602     };
603     Stream.prototype.parseOID = function (start, end, maxLength) {
604         var s = "";
605         var n = new Int10();
606         var bits = 0;
607         for (var i = start; i < end; ++i) {
608             var v = this.get(i);
609             n.mulAdd(128, v & 0x7F);
610             bits += 7;
611             if (!(v & 0x80)) { // finished
612                 if (s === "") {
613                     n = n.simplify();
614                     if (n instanceof Int10) {
615                         n.sub(80);
616                         s = "2." + n.toString();
617                     }
618                     else {
619                         var m = n < 80 ? n < 40 ? 0 : 1 : 2;
620                         s = m + "." + (n - m * 40);
621                     }
622                 }
623                 else {
624                     s += "." + n.toString();
625                 }
626                 if (s.length > maxLength) {
627                     return stringCut(s, maxLength);
628                 }
629                 n = new Int10();
630                 bits = 0;
631             }
632         }
633         if (bits > 0) {
634             s += ".incomplete";
635         }
636         return s;
637     };
638     return Stream;
639 }());
640 var ASN1 = /** @class */ (function () {
641     function ASN1(stream, header, length, tag, sub) {
642         if (!(tag instanceof ASN1Tag)) {
643             throw new Error("Invalid tag value.");
644         }
645         this.stream = stream;
646         this.header = header;
647         this.length = length;
648         this.tag = tag;
649         this.sub = sub;
650     }
651     ASN1.prototype.typeName = function () {
652         switch (this.tag.tagClass) {
653             case 0: // universal
654                 switch (this.tag.tagNumber) {
655                     case 0x00:
656                         return "EOC";
657                     case 0x01:
658                         return "BOOLEAN";
659                     case 0x02:
660                         return "INTEGER";
661                     case 0x03:
662                         return "BIT_STRING";
663                     case 0x04:
664                         return "OCTET_STRING";
665                     case 0x05:
666                         return "NULL";
667                     case 0x06:
668                         return "OBJECT_IDENTIFIER";
669                     case 0x07:
670                         return "ObjectDescriptor";
671                     case 0x08:
672                         return "EXTERNAL";
673                     case 0x09:
674                         return "REAL";
675                     case 0x0A:
676                         return "ENUMERATED";
677                     case 0x0B:
678                         return "EMBEDDED_PDV";
679                     case 0x0C:
680                         return "UTF8String";
681                     case 0x10:
682                         return "SEQUENCE";
683                     case 0x11:
684                         return "SET";
685                     case 0x12:
686                         return "NumericString";
687                     case 0x13:
688                         return "PrintableString"; // ASCII subset
689                     case 0x14:
690                         return "TeletexString"; // aka T61String
691                     case 0x15:
692                         return "VideotexString";
693                     case 0x16:
694                         return "IA5String"; // ASCII
695                     case 0x17:
696                         return "UTCTime";
697                     case 0x18:
698                         return "GeneralizedTime";
699                     case 0x19:
700                         return "GraphicString";
701                     case 0x1A:
702                         return "VisibleString"; // ASCII subset
703                     case 0x1B:
704                         return "GeneralString";
705                     case 0x1C:
706                         return "UniversalString";
707                     case 0x1E:
708                         return "BMPString";
709                 }
710                 return "Universal_" + this.tag.tagNumber.toString();
711             case 1:
712                 return "Application_" + this.tag.tagNumber.toString();
713             case 2:
714                 return "[" + this.tag.tagNumber.toString() + "]"; // Context
715             case 3:
716                 return "Private_" + this.tag.tagNumber.toString();
717         }
718     };
719     ASN1.prototype.content = function (maxLength) {
720         if (this.tag === undefined) {
721             return null;
722         }
723         if (maxLength === undefined) {
724             maxLength = Infinity;
725         }
726         var content = this.posContent();
727         var len = Math.abs(this.length);
728         if (!this.tag.isUniversal()) {
729             if (this.sub !== null) {
730                 return "(" + this.sub.length + " elem)";
731             }
732             return this.stream.parseOctetString(content, content + len, maxLength);
733         }
734         switch (this.tag.tagNumber) {
735             case 0x01: // BOOLEAN
736                 return (this.stream.get(content) === 0) ? "false" : "true";
737             case 0x02: // INTEGER
738                 return this.stream.parseInteger(content, content + len);
739             case 0x03: // BIT_STRING
740                 return this.sub ? "(" + this.sub.length + " elem)" :
741                     this.stream.parseBitString(content, content + len, maxLength);
742             case 0x04: // OCTET_STRING
743                 return this.sub ? "(" + this.sub.length + " elem)" :
744                     this.stream.parseOctetString(content, content + len, maxLength);
745             // case 0x05: // NULL
746             case 0x06: // OBJECT_IDENTIFIER
747                 return this.stream.parseOID(content, content + len, maxLength);
748             // case 0x07: // ObjectDescriptor
749             // case 0x08: // EXTERNAL
750             // case 0x09: // REAL
751             // case 0x0A: // ENUMERATED
752             // case 0x0B: // EMBEDDED_PDV
753             case 0x10: // SEQUENCE
754             case 0x11: // SET
755                 if (this.sub !== null) {
756                     return "(" + this.sub.length + " elem)";
757                 }
758                 else {
759                     return "(no elem)";
760                 }
761             case 0x0C: // UTF8String
762                 return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
763             case 0x12: // NumericString
764             case 0x13: // PrintableString
765             case 0x14: // TeletexString
766             case 0x15: // VideotexString
767             case 0x16: // IA5String
768             // case 0x19: // GraphicString
769             case 0x1A: // VisibleString
770                 // case 0x1B: // GeneralString
771                 // case 0x1C: // UniversalString
772                 return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
773             case 0x1E: // BMPString
774                 return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
775             case 0x17: // UTCTime
776             case 0x18: // GeneralizedTime
777                 return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
778         }
779         return null;
780     };
781     ASN1.prototype.toString = function () {
782         return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
783     };
784     ASN1.prototype.toPrettyString = function (indent) {
785         if (indent === undefined) {
786             indent = "";
787         }
788         var s = indent + this.typeName() + " @" + this.stream.pos;
789         if (this.length >= 0) {
790             s += "+";
791         }
792         s += this.length;
793         if (this.tag.tagConstructed) {
794             s += " (constructed)";
795         }
796         else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
797             s += " (encapsulates)";
798         }
799         s += "\n";
800         if (this.sub !== null) {
801             indent += "  ";
802             for (var i = 0, max = this.sub.length; i < max; ++i) {
803                 s += this.sub[i].toPrettyString(indent);
804             }
805         }
806         return s;
807     };
808     ASN1.prototype.posStart = function () {
809         return this.stream.pos;
810     };
811     ASN1.prototype.posContent = function () {
812         return this.stream.pos + this.header;
813     };
814     ASN1.prototype.posEnd = function () {
815         return this.stream.pos + this.header + Math.abs(this.length);
816     };
817     ASN1.prototype.toHexString = function () {
818         return this.stream.hexDump(this.posStart(), this.posEnd(), true);
819     };
820     ASN1.decodeLength = function (stream) {
821         var buf = stream.get();
822         var len = buf & 0x7F;
823         if (len == buf) {
824             return len;
825         }
826         // no reason to use Int10, as it would be a huge buffer anyways
827         if (len > 6) {
828             throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
829         }
830         if (len === 0) {
831             return null;
832         } // undefined
833         buf = 0;
834         for (var i = 0; i < len; ++i) {
835             buf = (buf * 256) + stream.get();
836         }
837         return buf;
838     };
839     /**
840      * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
841      * @returns {string}
842      * @public
843      */
844     ASN1.prototype.getHexStringValue = function () {
845         var hexString = this.toHexString();
846         var offset = this.header * 2;
847         var length = this.length * 2;
848         return hexString.substr(offset, length);
849     };
850     ASN1.decode = function (str) {
851         var stream;
852         if (!(str instanceof Stream)) {
853             stream = new Stream(str, 0);
854         }
855         else {
856             stream = str;
857         }
858         var streamStart = new Stream(stream);
859         var tag = new ASN1Tag(stream);
860         var len = ASN1.decodeLength(stream);
861         var start = stream.pos;
862         var header = start - streamStart.pos;
863         var sub = null;
864         var getSub = function () {
865             var ret = [];
866             if (len !== null) {
867                 // definite length
868                 var end = start + len;
869                 while (stream.pos < end) {
870                     ret[ret.length] = ASN1.decode(stream);
871                 }
872                 if (stream.pos != end) {
873                     throw new Error("Content size is not correct for container starting at offset " + start);
874                 }
875             }
876             else {
877                 // undefined length
878                 try {
879                     for (;;) {
880                         var s = ASN1.decode(stream);
881                         if (s.tag.isEOC()) {
882                             break;
883                         }
884                         ret[ret.length] = s;
885                     }
886                     len = start - stream.pos; // undefined lengths are represented as negative values
887                 }
888                 catch (e) {
889                     throw new Error("Exception while decoding undefined length content: " + e);
890                 }
891             }
892             return ret;
893         };
894         if (tag.tagConstructed) {
895             // must have valid content
896             sub = getSub();
897         }
898         else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
899             // sometimes BitString and OctetString are used to encapsulate ASN.1
900             try {
901                 if (tag.tagNumber == 0x03) {
902                     if (stream.get() != 0) {
903                         throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
904                     }
905                 }
906                 sub = getSub();
907                 for (var i = 0; i < sub.length; ++i) {
908                     if (sub[i].tag.isEOC()) {
909                         throw new Error("EOC is not supposed to be actual content.");
910                     }
911                 }
912             }
913             catch (e) {
914                 // but silently ignore when they don't
915                 sub = null;
916             }
917         }
918         if (sub === null) {
919             if (len === null) {
920                 throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
921             }
922             stream.pos = start + Math.abs(len);
923         }
924         return new ASN1(streamStart, header, len, tag, sub);
925     };
926     return ASN1;
927 }());
928 var ASN1Tag = /** @class */ (function () {
929     function ASN1Tag(stream) {
930         var buf = stream.get();
931         this.tagClass = buf >> 6;
932         this.tagConstructed = ((buf & 0x20) !== 0);
933         this.tagNumber = buf & 0x1F;
934         if (this.tagNumber == 0x1F) { // long tag
935             var n = new Int10();
936             do {
937                 buf = stream.get();
938                 n.mulAdd(128, buf & 0x7F);
939             } while (buf & 0x80);
940             this.tagNumber = n.simplify();
941         }
942     }
943     ASN1Tag.prototype.isUniversal = function () {
944         return this.tagClass === 0x00;
945     };
946     ASN1Tag.prototype.isEOC = function () {
947         return this.tagClass === 0x00 && this.tagNumber === 0x00;
948     };
949     return ASN1Tag;
950 }());
951
952 // Copyright (c) 2005  Tom Wu
953 // Bits per digit
954 var dbits;
955 // JavaScript engine analysis
956 var canary = 0xdeadbeefcafe;
957 var j_lm = ((canary & 0xffffff) == 0xefcafe);
958 //#region
959 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, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
960 var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
961 //#endregion
962 // (public) Constructor
963 var BigInteger = /** @class */ (function () {
964     function BigInteger(a, b, c) {
965         if (a != null) {
966             if ("number" == typeof a) {
967                 this.fromNumber(a, b, c);
968             }
969             else if (b == null && "string" != typeof a) {
970                 this.fromString(a, 256);
971             }
972             else {
973                 this.fromString(a, b);
974             }
975         }
976     }
977     //#region PUBLIC
978     // BigInteger.prototype.toString = bnToString;
979     // (public) return string representation in given radix
980     BigInteger.prototype.toString = function (b) {
981         if (this.s < 0) {
982             return "-" + this.negate().toString(b);
983         }
984         var k;
985         if (b == 16) {
986             k = 4;
987         }
988         else if (b == 8) {
989             k = 3;
990         }
991         else if (b == 2) {
992             k = 1;
993         }
994         else if (b == 32) {
995             k = 5;
996         }
997         else if (b == 4) {
998             k = 2;
999         }
1000         else {
1001             return this.toRadix(b);
1002         }
1003         var km = (1 << k) - 1;
1004         var d;
1005         var m = false;
1006         var r = "";
1007         var i = this.t;
1008         var p = this.DB - (i * this.DB) % k;
1009         if (i-- > 0) {
1010             if (p < this.DB && (d = this[i] >> p) > 0) {
1011                 m = true;
1012                 r = int2char(d);
1013             }
1014             while (i >= 0) {
1015                 if (p < k) {
1016                     d = (this[i] & ((1 << p) - 1)) << (k - p);
1017                     d |= this[--i] >> (p += this.DB - k);
1018                 }
1019                 else {
1020                     d = (this[i] >> (p -= k)) & km;
1021                     if (p <= 0) {
1022                         p += this.DB;
1023                         --i;
1024                     }
1025                 }
1026                 if (d > 0) {
1027                     m = true;
1028                 }
1029                 if (m) {
1030                     r += int2char(d);
1031                 }
1032             }
1033         }
1034         return m ? r : "0";
1035     };
1036     // BigInteger.prototype.negate = bnNegate;
1037     // (public) -this
1038     BigInteger.prototype.negate = function () {
1039         var r = nbi();
1040         BigInteger.ZERO.subTo(this, r);
1041         return r;
1042     };
1043     // BigInteger.prototype.abs = bnAbs;
1044     // (public) |this|
1045     BigInteger.prototype.abs = function () {
1046         return (this.s < 0) ? this.negate() : this;
1047     };
1048     // BigInteger.prototype.compareTo = bnCompareTo;
1049     // (public) return + if this > a, - if this < a, 0 if equal
1050     BigInteger.prototype.compareTo = function (a) {
1051         var r = this.s - a.s;
1052         if (r != 0) {
1053             return r;
1054         }
1055         var i = this.t;
1056         r = i - a.t;
1057         if (r != 0) {
1058             return (this.s < 0) ? -r : r;
1059         }
1060         while (--i >= 0) {
1061             if ((r = this[i] - a[i]) != 0) {
1062                 return r;
1063             }
1064         }
1065         return 0;
1066     };
1067     // BigInteger.prototype.bitLength = bnBitLength;
1068     // (public) return the number of bits in "this"
1069     BigInteger.prototype.bitLength = function () {
1070         if (this.t <= 0) {
1071             return 0;
1072         }
1073         return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
1074     };
1075     // BigInteger.prototype.mod = bnMod;
1076     // (public) this mod a
1077     BigInteger.prototype.mod = function (a) {
1078         var r = nbi();
1079         this.abs().divRemTo(a, null, r);
1080         if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
1081             a.subTo(r, r);
1082         }
1083         return r;
1084     };
1085     // BigInteger.prototype.modPowInt = bnModPowInt;
1086     // (public) this^e % m, 0 <= e < 2^32
1087     BigInteger.prototype.modPowInt = function (e, m) {
1088         var z;
1089         if (e < 256 || m.isEven()) {
1090             z = new Classic(m);
1091         }
1092         else {
1093             z = new Montgomery(m);
1094         }
1095         return this.exp(e, z);
1096     };
1097     // BigInteger.prototype.clone = bnClone;
1098     // (public)
1099     BigInteger.prototype.clone = function () {
1100         var r = nbi();
1101         this.copyTo(r);
1102         return r;
1103     };
1104     // BigInteger.prototype.intValue = bnIntValue;
1105     // (public) return value as integer
1106     BigInteger.prototype.intValue = function () {
1107         if (this.s < 0) {
1108             if (this.t == 1) {
1109                 return this[0] - this.DV;
1110             }
1111             else if (this.t == 0) {
1112                 return -1;
1113             }
1114         }
1115         else if (this.t == 1) {
1116             return this[0];
1117         }
1118         else if (this.t == 0) {
1119             return 0;
1120         }
1121         // assumes 16 < DB < 32
1122         return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
1123     };
1124     // BigInteger.prototype.byteValue = bnByteValue;
1125     // (public) return value as byte
1126     BigInteger.prototype.byteValue = function () {
1127         return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
1128     };
1129     // BigInteger.prototype.shortValue = bnShortValue;
1130     // (public) return value as short (assumes DB>=16)
1131     BigInteger.prototype.shortValue = function () {
1132         return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
1133     };
1134     // BigInteger.prototype.signum = bnSigNum;
1135     // (public) 0 if this == 0, 1 if this > 0
1136     BigInteger.prototype.signum = function () {
1137         if (this.s < 0) {
1138             return -1;
1139         }
1140         else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
1141             return 0;
1142         }
1143         else {
1144             return 1;
1145         }
1146     };
1147     // BigInteger.prototype.toByteArray = bnToByteArray;
1148     // (public) convert to bigendian byte array
1149     BigInteger.prototype.toByteArray = function () {
1150         var i = this.t;
1151         var r = [];
1152         r[0] = this.s;
1153         var p = this.DB - (i * this.DB) % 8;
1154         var d;
1155         var k = 0;
1156         if (i-- > 0) {
1157             if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
1158                 r[k++] = d | (this.s << (this.DB - p));
1159             }
1160             while (i >= 0) {
1161                 if (p < 8) {
1162                     d = (this[i] & ((1 << p) - 1)) << (8 - p);
1163                     d |= this[--i] >> (p += this.DB - 8);
1164                 }
1165                 else {
1166                     d = (this[i] >> (p -= 8)) & 0xff;
1167                     if (p <= 0) {
1168                         p += this.DB;
1169                         --i;
1170                     }
1171                 }
1172                 if ((d & 0x80) != 0) {
1173                     d |= -256;
1174                 }
1175                 if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
1176                     ++k;
1177                 }
1178                 if (k > 0 || d != this.s) {
1179                     r[k++] = d;
1180                 }
1181             }
1182         }
1183         return r;
1184     };
1185     // BigInteger.prototype.equals = bnEquals;
1186     BigInteger.prototype.equals = function (a) {
1187         return (this.compareTo(a) == 0);
1188     };
1189     // BigInteger.prototype.min = bnMin;
1190     BigInteger.prototype.min = function (a) {
1191         return (this.compareTo(a) < 0) ? this : a;
1192     };
1193     // BigInteger.prototype.max = bnMax;
1194     BigInteger.prototype.max = function (a) {
1195         return (this.compareTo(a) > 0) ? this : a;
1196     };
1197     // BigInteger.prototype.and = bnAnd;
1198     BigInteger.prototype.and = function (a) {
1199         var r = nbi();
1200         this.bitwiseTo(a, op_and, r);
1201         return r;
1202     };
1203     // BigInteger.prototype.or = bnOr;
1204     BigInteger.prototype.or = function (a) {
1205         var r = nbi();
1206         this.bitwiseTo(a, op_or, r);
1207         return r;
1208     };
1209     // BigInteger.prototype.xor = bnXor;
1210     BigInteger.prototype.xor = function (a) {
1211         var r = nbi();
1212         this.bitwiseTo(a, op_xor, r);
1213         return r;
1214     };
1215     // BigInteger.prototype.andNot = bnAndNot;
1216     BigInteger.prototype.andNot = function (a) {
1217         var r = nbi();
1218         this.bitwiseTo(a, op_andnot, r);
1219         return r;
1220     };
1221     // BigInteger.prototype.not = bnNot;
1222     // (public) ~this
1223     BigInteger.prototype.not = function () {
1224         var r = nbi();
1225         for (var i = 0; i < this.t; ++i) {
1226             r[i] = this.DM & ~this[i];
1227         }
1228         r.t = this.t;
1229         r.s = ~this.s;
1230         return r;
1231     };
1232     // BigInteger.prototype.shiftLeft = bnShiftLeft;
1233     // (public) this << n
1234     BigInteger.prototype.shiftLeft = function (n) {
1235         var r = nbi();
1236         if (n < 0) {
1237             this.rShiftTo(-n, r);
1238         }
1239         else {
1240             this.lShiftTo(n, r);
1241         }
1242         return r;
1243     };
1244     // BigInteger.prototype.shiftRight = bnShiftRight;
1245     // (public) this >> n
1246     BigInteger.prototype.shiftRight = function (n) {
1247         var r = nbi();
1248         if (n < 0) {
1249             this.lShiftTo(-n, r);
1250         }
1251         else {
1252             this.rShiftTo(n, r);
1253         }
1254         return r;
1255     };
1256     // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
1257     // (public) returns index of lowest 1-bit (or -1 if none)
1258     BigInteger.prototype.getLowestSetBit = function () {
1259         for (var i = 0; i < this.t; ++i) {
1260             if (this[i] != 0) {
1261                 return i * this.DB + lbit(this[i]);
1262             }
1263         }
1264         if (this.s < 0) {
1265             return this.t * this.DB;
1266         }
1267         return -1;
1268     };
1269     // BigInteger.prototype.bitCount = bnBitCount;
1270     // (public) return number of set bits
1271     BigInteger.prototype.bitCount = function () {
1272         var r = 0;
1273         var x = this.s & this.DM;
1274         for (var i = 0; i < this.t; ++i) {
1275             r += cbit(this[i] ^ x);
1276         }
1277         return r;
1278     };
1279     // BigInteger.prototype.testBit = bnTestBit;
1280     // (public) true iff nth bit is set
1281     BigInteger.prototype.testBit = function (n) {
1282         var j = Math.floor(n / this.DB);
1283         if (j >= this.t) {
1284             return (this.s != 0);
1285         }
1286         return ((this[j] & (1 << (n % this.DB))) != 0);
1287     };
1288     // BigInteger.prototype.setBit = bnSetBit;
1289     // (public) this | (1<<n)
1290     BigInteger.prototype.setBit = function (n) {
1291         return this.changeBit(n, op_or);
1292     };
1293     // BigInteger.prototype.clearBit = bnClearBit;
1294     // (public) this & ~(1<<n)
1295     BigInteger.prototype.clearBit = function (n) {
1296         return this.changeBit(n, op_andnot);
1297     };
1298     // BigInteger.prototype.flipBit = bnFlipBit;
1299     // (public) this ^ (1<<n)
1300     BigInteger.prototype.flipBit = function (n) {
1301         return this.changeBit(n, op_xor);
1302     };
1303     // BigInteger.prototype.add = bnAdd;
1304     // (public) this + a
1305     BigInteger.prototype.add = function (a) {
1306         var r = nbi();
1307         this.addTo(a, r);
1308         return r;
1309     };
1310     // BigInteger.prototype.subtract = bnSubtract;
1311     // (public) this - a
1312     BigInteger.prototype.subtract = function (a) {
1313         var r = nbi();
1314         this.subTo(a, r);
1315         return r;
1316     };
1317     // BigInteger.prototype.multiply = bnMultiply;
1318     // (public) this * a
1319     BigInteger.prototype.multiply = function (a) {
1320         var r = nbi();
1321         this.multiplyTo(a, r);
1322         return r;
1323     };
1324     // BigInteger.prototype.divide = bnDivide;
1325     // (public) this / a
1326     BigInteger.prototype.divide = function (a) {
1327         var r = nbi();
1328         this.divRemTo(a, r, null);
1329         return r;
1330     };
1331     // BigInteger.prototype.remainder = bnRemainder;
1332     // (public) this % a
1333     BigInteger.prototype.remainder = function (a) {
1334         var r = nbi();
1335         this.divRemTo(a, null, r);
1336         return r;
1337     };
1338     // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
1339     // (public) [this/a,this%a]
1340     BigInteger.prototype.divideAndRemainder = function (a) {
1341         var q = nbi();
1342         var r = nbi();
1343         this.divRemTo(a, q, r);
1344         return [q, r];
1345     };
1346     // BigInteger.prototype.modPow = bnModPow;
1347     // (public) this^e % m (HAC 14.85)
1348     BigInteger.prototype.modPow = function (e, m) {
1349         var i = e.bitLength();
1350         var k;
1351         var r = nbv(1);
1352         var z;
1353         if (i <= 0) {
1354             return r;
1355         }
1356         else if (i < 18) {
1357             k = 1;
1358         }
1359         else if (i < 48) {
1360             k = 3;
1361         }
1362         else if (i < 144) {
1363             k = 4;
1364         }
1365         else if (i < 768) {
1366             k = 5;
1367         }
1368         else {
1369             k = 6;
1370         }
1371         if (i < 8) {
1372             z = new Classic(m);
1373         }
1374         else if (m.isEven()) {
1375             z = new Barrett(m);
1376         }
1377         else {
1378             z = new Montgomery(m);
1379         }
1380         // precomputation
1381         var g = [];
1382         var n = 3;
1383         var k1 = k - 1;
1384         var km = (1 << k) - 1;
1385         g[1] = z.convert(this);
1386         if (k > 1) {
1387             var g2 = nbi();
1388             z.sqrTo(g[1], g2);
1389             while (n <= km) {
1390                 g[n] = nbi();
1391                 z.mulTo(g2, g[n - 2], g[n]);
1392                 n += 2;
1393             }
1394         }
1395         var j = e.t - 1;
1396         var w;
1397         var is1 = true;
1398         var r2 = nbi();
1399         var t;
1400         i = nbits(e[j]) - 1;
1401         while (j >= 0) {
1402             if (i >= k1) {
1403                 w = (e[j] >> (i - k1)) & km;
1404             }
1405             else {
1406                 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
1407                 if (j > 0) {
1408                     w |= e[j - 1] >> (this.DB + i - k1);
1409                 }
1410             }
1411             n = k;
1412             while ((w & 1) == 0) {
1413                 w >>= 1;
1414                 --n;
1415             }
1416             if ((i -= n) < 0) {
1417                 i += this.DB;
1418                 --j;
1419             }
1420             if (is1) { // ret == 1, don't bother squaring or multiplying it
1421                 g[w].copyTo(r);
1422                 is1 = false;
1423             }
1424             else {
1425                 while (n > 1) {
1426                     z.sqrTo(r, r2);
1427                     z.sqrTo(r2, r);
1428                     n -= 2;
1429                 }
1430                 if (n > 0) {
1431                     z.sqrTo(r, r2);
1432                 }
1433                 else {
1434                     t = r;
1435                     r = r2;
1436                     r2 = t;
1437                 }
1438                 z.mulTo(r2, g[w], r);
1439             }
1440             while (j >= 0 && (e[j] & (1 << i)) == 0) {
1441                 z.sqrTo(r, r2);
1442                 t = r;
1443                 r = r2;
1444                 r2 = t;
1445                 if (--i < 0) {
1446                     i = this.DB - 1;
1447                     --j;
1448                 }
1449             }
1450         }
1451         return z.revert(r);
1452     };
1453     // BigInteger.prototype.modInverse = bnModInverse;
1454     // (public) 1/this % m (HAC 14.61)
1455     BigInteger.prototype.modInverse = function (m) {
1456         var ac = m.isEven();
1457         if ((this.isEven() && ac) || m.signum() == 0) {
1458             return BigInteger.ZERO;
1459         }
1460         var u = m.clone();
1461         var v = this.clone();
1462         var a = nbv(1);
1463         var b = nbv(0);
1464         var c = nbv(0);
1465         var d = nbv(1);
1466         while (u.signum() != 0) {
1467             while (u.isEven()) {
1468                 u.rShiftTo(1, u);
1469                 if (ac) {
1470                     if (!a.isEven() || !b.isEven()) {
1471                         a.addTo(this, a);
1472                         b.subTo(m, b);
1473                     }
1474                     a.rShiftTo(1, a);
1475                 }
1476                 else if (!b.isEven()) {
1477                     b.subTo(m, b);
1478                 }
1479                 b.rShiftTo(1, b);
1480             }
1481             while (v.isEven()) {
1482                 v.rShiftTo(1, v);
1483                 if (ac) {
1484                     if (!c.isEven() || !d.isEven()) {
1485                         c.addTo(this, c);
1486                         d.subTo(m, d);
1487                     }
1488                     c.rShiftTo(1, c);
1489                 }
1490                 else if (!d.isEven()) {
1491                     d.subTo(m, d);
1492                 }
1493                 d.rShiftTo(1, d);
1494             }
1495             if (u.compareTo(v) >= 0) {
1496                 u.subTo(v, u);
1497                 if (ac) {
1498                     a.subTo(c, a);
1499                 }
1500                 b.subTo(d, b);
1501             }
1502             else {
1503                 v.subTo(u, v);
1504                 if (ac) {
1505                     c.subTo(a, c);
1506                 }
1507                 d.subTo(b, d);
1508             }
1509         }
1510         if (v.compareTo(BigInteger.ONE) != 0) {
1511             return BigInteger.ZERO;
1512         }
1513         if (d.compareTo(m) >= 0) {
1514             return d.subtract(m);
1515         }
1516         if (d.signum() < 0) {
1517             d.addTo(m, d);
1518         }
1519         else {
1520             return d;
1521         }
1522         if (d.signum() < 0) {
1523             return d.add(m);
1524         }
1525         else {
1526             return d;
1527         }
1528     };
1529     // BigInteger.prototype.pow = bnPow;
1530     // (public) this^e
1531     BigInteger.prototype.pow = function (e) {
1532         return this.exp(e, new NullExp());
1533     };
1534     // BigInteger.prototype.gcd = bnGCD;
1535     // (public) gcd(this,a) (HAC 14.54)
1536     BigInteger.prototype.gcd = function (a) {
1537         var x = (this.s < 0) ? this.negate() : this.clone();
1538         var y = (a.s < 0) ? a.negate() : a.clone();
1539         if (x.compareTo(y) < 0) {
1540             var t = x;
1541             x = y;
1542             y = t;
1543         }
1544         var i = x.getLowestSetBit();
1545         var g = y.getLowestSetBit();
1546         if (g < 0) {
1547             return x;
1548         }
1549         if (i < g) {
1550             g = i;
1551         }
1552         if (g > 0) {
1553             x.rShiftTo(g, x);
1554             y.rShiftTo(g, y);
1555         }
1556         while (x.signum() > 0) {
1557             if ((i = x.getLowestSetBit()) > 0) {
1558                 x.rShiftTo(i, x);
1559             }
1560             if ((i = y.getLowestSetBit()) > 0) {
1561                 y.rShiftTo(i, y);
1562             }
1563             if (x.compareTo(y) >= 0) {
1564                 x.subTo(y, x);
1565                 x.rShiftTo(1, x);
1566             }
1567             else {
1568                 y.subTo(x, y);
1569                 y.rShiftTo(1, y);
1570             }
1571         }
1572         if (g > 0) {
1573             y.lShiftTo(g, y);
1574         }
1575         return y;
1576     };
1577     // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
1578     // (public) test primality with certainty >= 1-.5^t
1579     BigInteger.prototype.isProbablePrime = function (t) {
1580         var i;
1581         var x = this.abs();
1582         if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
1583             for (i = 0; i < lowprimes.length; ++i) {
1584                 if (x[0] == lowprimes[i]) {
1585                     return true;
1586                 }
1587             }
1588             return false;
1589         }
1590         if (x.isEven()) {
1591             return false;
1592         }
1593         i = 1;
1594         while (i < lowprimes.length) {
1595             var m = lowprimes[i];
1596             var j = i + 1;
1597             while (j < lowprimes.length && m < lplim) {
1598                 m *= lowprimes[j++];
1599             }
1600             m = x.modInt(m);
1601             while (i < j) {
1602                 if (m % lowprimes[i++] == 0) {
1603                     return false;
1604                 }
1605             }
1606         }
1607         return x.millerRabin(t);
1608     };
1609     //#endregion PUBLIC
1610     //#region PROTECTED
1611     // BigInteger.prototype.copyTo = bnpCopyTo;
1612     // (protected) copy this to r
1613     BigInteger.prototype.copyTo = function (r) {
1614         for (var i = this.t - 1; i >= 0; --i) {
1615             r[i] = this[i];
1616         }
1617         r.t = this.t;
1618         r.s = this.s;
1619     };
1620     // BigInteger.prototype.fromInt = bnpFromInt;
1621     // (protected) set from integer value x, -DV <= x < DV
1622     BigInteger.prototype.fromInt = function (x) {
1623         this.t = 1;
1624         this.s = (x < 0) ? -1 : 0;
1625         if (x > 0) {
1626             this[0] = x;
1627         }
1628         else if (x < -1) {
1629             this[0] = x + this.DV;
1630         }
1631         else {
1632             this.t = 0;
1633         }
1634     };
1635     // BigInteger.prototype.fromString = bnpFromString;
1636     // (protected) set from string and radix
1637     BigInteger.prototype.fromString = function (s, b) {
1638         var k;
1639         if (b == 16) {
1640             k = 4;
1641         }
1642         else if (b == 8) {
1643             k = 3;
1644         }
1645         else if (b == 256) {
1646             k = 8;
1647             /* byte array */
1648         }
1649         else if (b == 2) {
1650             k = 1;
1651         }
1652         else if (b == 32) {
1653             k = 5;
1654         }
1655         else if (b == 4) {
1656             k = 2;
1657         }
1658         else {
1659             this.fromRadix(s, b);
1660             return;
1661         }
1662         this.t = 0;
1663         this.s = 0;
1664         var i = s.length;
1665         var mi = false;
1666         var sh = 0;
1667         while (--i >= 0) {
1668             var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
1669             if (x < 0) {
1670                 if (s.charAt(i) == "-") {
1671                     mi = true;
1672                 }
1673                 continue;
1674             }
1675             mi = false;
1676             if (sh == 0) {
1677                 this[this.t++] = x;
1678             }
1679             else if (sh + k > this.DB) {
1680                 this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
1681                 this[this.t++] = (x >> (this.DB - sh));
1682             }
1683             else {
1684                 this[this.t - 1] |= x << sh;
1685             }
1686             sh += k;
1687             if (sh >= this.DB) {
1688                 sh -= this.DB;
1689             }
1690         }
1691         if (k == 8 && ((+s[0]) & 0x80) != 0) {
1692             this.s = -1;
1693             if (sh > 0) {
1694                 this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
1695             }
1696         }
1697         this.clamp();
1698         if (mi) {
1699             BigInteger.ZERO.subTo(this, this);
1700         }
1701     };
1702     // BigInteger.prototype.clamp = bnpClamp;
1703     // (protected) clamp off excess high words
1704     BigInteger.prototype.clamp = function () {
1705         var c = this.s & this.DM;
1706         while (this.t > 0 && this[this.t - 1] == c) {
1707             --this.t;
1708         }
1709     };
1710     // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
1711     // (protected) r = this << n*DB
1712     BigInteger.prototype.dlShiftTo = function (n, r) {
1713         var i;
1714         for (i = this.t - 1; i >= 0; --i) {
1715             r[i + n] = this[i];
1716         }
1717         for (i = n - 1; i >= 0; --i) {
1718             r[i] = 0;
1719         }
1720         r.t = this.t + n;
1721         r.s = this.s;
1722     };
1723     // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
1724     // (protected) r = this >> n*DB
1725     BigInteger.prototype.drShiftTo = function (n, r) {
1726         for (var i = n; i < this.t; ++i) {
1727             r[i - n] = this[i];
1728         }
1729         r.t = Math.max(this.t - n, 0);
1730         r.s = this.s;
1731     };
1732     // BigInteger.prototype.lShiftTo = bnpLShiftTo;
1733     // (protected) r = this << n
1734     BigInteger.prototype.lShiftTo = function (n, r) {
1735         var bs = n % this.DB;
1736         var cbs = this.DB - bs;
1737         var bm = (1 << cbs) - 1;
1738         var ds = Math.floor(n / this.DB);
1739         var c = (this.s << bs) & this.DM;
1740         for (var i = this.t - 1; i >= 0; --i) {
1741             r[i + ds + 1] = (this[i] >> cbs) | c;
1742             c = (this[i] & bm) << bs;
1743         }
1744         for (var i = ds - 1; i >= 0; --i) {
1745             r[i] = 0;
1746         }
1747         r[ds] = c;
1748         r.t = this.t + ds + 1;
1749         r.s = this.s;
1750         r.clamp();
1751     };
1752     // BigInteger.prototype.rShiftTo = bnpRShiftTo;
1753     // (protected) r = this >> n
1754     BigInteger.prototype.rShiftTo = function (n, r) {
1755         r.s = this.s;
1756         var ds = Math.floor(n / this.DB);
1757         if (ds >= this.t) {
1758             r.t = 0;
1759             return;
1760         }
1761         var bs = n % this.DB;
1762         var cbs = this.DB - bs;
1763         var bm = (1 << bs) - 1;
1764         r[0] = this[ds] >> bs;
1765         for (var i = ds + 1; i < this.t; ++i) {
1766             r[i - ds - 1] |= (this[i] & bm) << cbs;
1767             r[i - ds] = this[i] >> bs;
1768         }
1769         if (bs > 0) {
1770             r[this.t - ds - 1] |= (this.s & bm) << cbs;
1771         }
1772         r.t = this.t - ds;
1773         r.clamp();
1774     };
1775     // BigInteger.prototype.subTo = bnpSubTo;
1776     // (protected) r = this - a
1777     BigInteger.prototype.subTo = function (a, r) {
1778         var i = 0;
1779         var c = 0;
1780         var m = Math.min(a.t, this.t);
1781         while (i < m) {
1782             c += this[i] - a[i];
1783             r[i++] = c & this.DM;
1784             c >>= this.DB;
1785         }
1786         if (a.t < this.t) {
1787             c -= a.s;
1788             while (i < this.t) {
1789                 c += this[i];
1790                 r[i++] = c & this.DM;
1791                 c >>= this.DB;
1792             }
1793             c += this.s;
1794         }
1795         else {
1796             c += this.s;
1797             while (i < a.t) {
1798                 c -= a[i];
1799                 r[i++] = c & this.DM;
1800                 c >>= this.DB;
1801             }
1802             c -= a.s;
1803         }
1804         r.s = (c < 0) ? -1 : 0;
1805         if (c < -1) {
1806             r[i++] = this.DV + c;
1807         }
1808         else if (c > 0) {
1809             r[i++] = c;
1810         }
1811         r.t = i;
1812         r.clamp();
1813     };
1814     // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
1815     // (protected) r = this * a, r != this,a (HAC 14.12)
1816     // "this" should be the larger one if appropriate.
1817     BigInteger.prototype.multiplyTo = function (a, r) {
1818         var x = this.abs();
1819         var y = a.abs();
1820         var i = x.t;
1821         r.t = i + y.t;
1822         while (--i >= 0) {
1823             r[i] = 0;
1824         }
1825         for (i = 0; i < y.t; ++i) {
1826             r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
1827         }
1828         r.s = 0;
1829         r.clamp();
1830         if (this.s != a.s) {
1831             BigInteger.ZERO.subTo(r, r);
1832         }
1833     };
1834     // BigInteger.prototype.squareTo = bnpSquareTo;
1835     // (protected) r = this^2, r != this (HAC 14.16)
1836     BigInteger.prototype.squareTo = function (r) {
1837         var x = this.abs();
1838         var i = r.t = 2 * x.t;
1839         while (--i >= 0) {
1840             r[i] = 0;
1841         }
1842         for (i = 0; i < x.t - 1; ++i) {
1843             var c = x.am(i, x[i], r, 2 * i, 0, 1);
1844             if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
1845                 r[i + x.t] -= x.DV;
1846                 r[i + x.t + 1] = 1;
1847             }
1848         }
1849         if (r.t > 0) {
1850             r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
1851         }
1852         r.s = 0;
1853         r.clamp();
1854     };
1855     // BigInteger.prototype.divRemTo = bnpDivRemTo;
1856     // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
1857     // r != q, this != m.  q or r may be null.
1858     BigInteger.prototype.divRemTo = function (m, q, r) {
1859         var pm = m.abs();
1860         if (pm.t <= 0) {
1861             return;
1862         }
1863         var pt = this.abs();
1864         if (pt.t < pm.t) {
1865             if (q != null) {
1866                 q.fromInt(0);
1867             }
1868             if (r != null) {
1869                 this.copyTo(r);
1870             }
1871             return;
1872         }
1873         if (r == null) {
1874             r = nbi();
1875         }
1876         var y = nbi();
1877         var ts = this.s;
1878         var ms = m.s;
1879         var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
1880         if (nsh > 0) {
1881             pm.lShiftTo(nsh, y);
1882             pt.lShiftTo(nsh, r);
1883         }
1884         else {
1885             pm.copyTo(y);
1886             pt.copyTo(r);
1887         }
1888         var ys = y.t;
1889         var y0 = y[ys - 1];
1890         if (y0 == 0) {
1891             return;
1892         }
1893         var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
1894         var d1 = this.FV / yt;
1895         var d2 = (1 << this.F1) / yt;
1896         var e = 1 << this.F2;
1897         var i = r.t;
1898         var j = i - ys;
1899         var t = (q == null) ? nbi() : q;
1900         y.dlShiftTo(j, t);
1901         if (r.compareTo(t) >= 0) {
1902             r[r.t++] = 1;
1903             r.subTo(t, r);
1904         }
1905         BigInteger.ONE.dlShiftTo(ys, t);
1906         t.subTo(y, y); // "negative" y so we can replace sub with am later
1907         while (y.t < ys) {
1908             y[y.t++] = 0;
1909         }
1910         while (--j >= 0) {
1911             // Estimate quotient digit
1912             var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
1913             if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
1914                 y.dlShiftTo(j, t);
1915                 r.subTo(t, r);
1916                 while (r[i] < --qd) {
1917                     r.subTo(t, r);
1918                 }
1919             }
1920         }
1921         if (q != null) {
1922             r.drShiftTo(ys, q);
1923             if (ts != ms) {
1924                 BigInteger.ZERO.subTo(q, q);
1925             }
1926         }
1927         r.t = ys;
1928         r.clamp();
1929         if (nsh > 0) {
1930             r.rShiftTo(nsh, r);
1931         } // Denormalize remainder
1932         if (ts < 0) {
1933             BigInteger.ZERO.subTo(r, r);
1934         }
1935     };
1936     // BigInteger.prototype.invDigit = bnpInvDigit;
1937     // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
1938     // justification:
1939     //         xy == 1 (mod m)
1940     //         xy =  1+km
1941     //   xy(2-xy) = (1+km)(1-km)
1942     // x[y(2-xy)] = 1-k^2m^2
1943     // x[y(2-xy)] == 1 (mod m^2)
1944     // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
1945     // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
1946     // JS multiply "overflows" differently from C/C++, so care is needed here.
1947     BigInteger.prototype.invDigit = function () {
1948         if (this.t < 1) {
1949             return 0;
1950         }
1951         var x = this[0];
1952         if ((x & 1) == 0) {
1953             return 0;
1954         }
1955         var y = x & 3; // y == 1/x mod 2^2
1956         y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
1957         y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
1958         y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
1959         // last step - calculate inverse mod DV directly;
1960         // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
1961         y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
1962         // we really want the negative inverse, and -DV < y < DV
1963         return (y > 0) ? this.DV - y : -y;
1964     };
1965     // BigInteger.prototype.isEven = bnpIsEven;
1966     // (protected) true iff this is even
1967     BigInteger.prototype.isEven = function () {
1968         return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
1969     };
1970     // BigInteger.prototype.exp = bnpExp;
1971     // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
1972     BigInteger.prototype.exp = function (e, z) {
1973         if (e > 0xffffffff || e < 1) {
1974             return BigInteger.ONE;
1975         }
1976         var r = nbi();
1977         var r2 = nbi();
1978         var g = z.convert(this);
1979         var i = nbits(e) - 1;
1980         g.copyTo(r);
1981         while (--i >= 0) {
1982             z.sqrTo(r, r2);
1983             if ((e & (1 << i)) > 0) {
1984                 z.mulTo(r2, g, r);
1985             }
1986             else {
1987                 var t = r;
1988                 r = r2;
1989                 r2 = t;
1990             }
1991         }
1992         return z.revert(r);
1993     };
1994     // BigInteger.prototype.chunkSize = bnpChunkSize;
1995     // (protected) return x s.t. r^x < DV
1996     BigInteger.prototype.chunkSize = function (r) {
1997         return Math.floor(Math.LN2 * this.DB / Math.log(r));
1998     };
1999     // BigInteger.prototype.toRadix = bnpToRadix;
2000     // (protected) convert to radix string
2001     BigInteger.prototype.toRadix = function (b) {
2002         if (b == null) {
2003             b = 10;
2004         }
2005         if (this.signum() == 0 || b < 2 || b > 36) {
2006             return "0";
2007         }
2008         var cs = this.chunkSize(b);
2009         var a = Math.pow(b, cs);
2010         var d = nbv(a);
2011         var y = nbi();
2012         var z = nbi();
2013         var r = "";
2014         this.divRemTo(d, y, z);
2015         while (y.signum() > 0) {
2016             r = (a + z.intValue()).toString(b).substr(1) + r;
2017             y.divRemTo(d, y, z);
2018         }
2019         return z.intValue().toString(b) + r;
2020     };
2021     // BigInteger.prototype.fromRadix = bnpFromRadix;
2022     // (protected) convert from radix string
2023     BigInteger.prototype.fromRadix = function (s, b) {
2024         this.fromInt(0);
2025         if (b == null) {
2026             b = 10;
2027         }
2028         var cs = this.chunkSize(b);
2029         var d = Math.pow(b, cs);
2030         var mi = false;
2031         var j = 0;
2032         var w = 0;
2033         for (var i = 0; i < s.length; ++i) {
2034             var x = intAt(s, i);
2035             if (x < 0) {
2036                 if (s.charAt(i) == "-" && this.signum() == 0) {
2037                     mi = true;
2038                 }
2039                 continue;
2040             }
2041             w = b * w + x;
2042             if (++j >= cs) {
2043                 this.dMultiply(d);
2044                 this.dAddOffset(w, 0);
2045                 j = 0;
2046                 w = 0;
2047             }
2048         }
2049         if (j > 0) {
2050             this.dMultiply(Math.pow(b, j));
2051             this.dAddOffset(w, 0);
2052         }
2053         if (mi) {
2054             BigInteger.ZERO.subTo(this, this);
2055         }
2056     };
2057     // BigInteger.prototype.fromNumber = bnpFromNumber;
2058     // (protected) alternate constructor
2059     BigInteger.prototype.fromNumber = function (a, b, c) {
2060         if ("number" == typeof b) {
2061             // new BigInteger(int,int,RNG)
2062             if (a < 2) {
2063                 this.fromInt(1);
2064             }
2065             else {
2066                 this.fromNumber(a, c);
2067                 if (!this.testBit(a - 1)) {
2068                     // force MSB set
2069                     this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2070                 }
2071                 if (this.isEven()) {
2072                     this.dAddOffset(1, 0);
2073                 } // force odd
2074                 while (!this.isProbablePrime(b)) {
2075                     this.dAddOffset(2, 0);
2076                     if (this.bitLength() > a) {
2077                         this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
2078                     }
2079                 }
2080             }
2081         }
2082         else {
2083             // new BigInteger(int,RNG)
2084             var x = [];
2085             var t = a & 7;
2086             x.length = (a >> 3) + 1;
2087             b.nextBytes(x);
2088             if (t > 0) {
2089                 x[0] &= ((1 << t) - 1);
2090             }
2091             else {
2092                 x[0] = 0;
2093             }
2094             this.fromString(x, 256);
2095         }
2096     };
2097     // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
2098     // (protected) r = this op a (bitwise)
2099     BigInteger.prototype.bitwiseTo = function (a, op, r) {
2100         var i;
2101         var f;
2102         var m = Math.min(a.t, this.t);
2103         for (i = 0; i < m; ++i) {
2104             r[i] = op(this[i], a[i]);
2105         }
2106         if (a.t < this.t) {
2107             f = a.s & this.DM;
2108             for (i = m; i < this.t; ++i) {
2109                 r[i] = op(this[i], f);
2110             }
2111             r.t = this.t;
2112         }
2113         else {
2114             f = this.s & this.DM;
2115             for (i = m; i < a.t; ++i) {
2116                 r[i] = op(f, a[i]);
2117             }
2118             r.t = a.t;
2119         }
2120         r.s = op(this.s, a.s);
2121         r.clamp();
2122     };
2123     // BigInteger.prototype.changeBit = bnpChangeBit;
2124     // (protected) this op (1<<n)
2125     BigInteger.prototype.changeBit = function (n, op) {
2126         var r = BigInteger.ONE.shiftLeft(n);
2127         this.bitwiseTo(r, op, r);
2128         return r;
2129     };
2130     // BigInteger.prototype.addTo = bnpAddTo;
2131     // (protected) r = this + a
2132     BigInteger.prototype.addTo = function (a, r) {
2133         var i = 0;
2134         var c = 0;
2135         var m = Math.min(a.t, this.t);
2136         while (i < m) {
2137             c += this[i] + a[i];
2138             r[i++] = c & this.DM;
2139             c >>= this.DB;
2140         }
2141         if (a.t < this.t) {
2142             c += a.s;
2143             while (i < this.t) {
2144                 c += this[i];
2145                 r[i++] = c & this.DM;
2146                 c >>= this.DB;
2147             }
2148             c += this.s;
2149         }
2150         else {
2151             c += this.s;
2152             while (i < a.t) {
2153                 c += a[i];
2154                 r[i++] = c & this.DM;
2155                 c >>= this.DB;
2156             }
2157             c += a.s;
2158         }
2159         r.s = (c < 0) ? -1 : 0;
2160         if (c > 0) {
2161             r[i++] = c;
2162         }
2163         else if (c < -1) {
2164             r[i++] = this.DV + c;
2165         }
2166         r.t = i;
2167         r.clamp();
2168     };
2169     // BigInteger.prototype.dMultiply = bnpDMultiply;
2170     // (protected) this *= n, this >= 0, 1 < n < DV
2171     BigInteger.prototype.dMultiply = function (n) {
2172         this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
2173         ++this.t;
2174         this.clamp();
2175     };
2176     // BigInteger.prototype.dAddOffset = bnpDAddOffset;
2177     // (protected) this += n << w words, this >= 0
2178     BigInteger.prototype.dAddOffset = function (n, w) {
2179         if (n == 0) {
2180             return;
2181         }
2182         while (this.t <= w) {
2183             this[this.t++] = 0;
2184         }
2185         this[w] += n;
2186         while (this[w] >= this.DV) {
2187             this[w] -= this.DV;
2188             if (++w >= this.t) {
2189                 this[this.t++] = 0;
2190             }
2191             ++this[w];
2192         }
2193     };
2194     // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
2195     // (protected) r = lower n words of "this * a", a.t <= n
2196     // "this" should be the larger one if appropriate.
2197     BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
2198         var i = Math.min(this.t + a.t, n);
2199         r.s = 0; // assumes a,this >= 0
2200         r.t = i;
2201         while (i > 0) {
2202             r[--i] = 0;
2203         }
2204         for (var j = r.t - this.t; i < j; ++i) {
2205             r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
2206         }
2207         for (var j = Math.min(a.t, n); i < j; ++i) {
2208             this.am(0, a[i], r, i, 0, n - i);
2209         }
2210         r.clamp();
2211     };
2212     // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
2213     // (protected) r = "this * a" without lower n words, n > 0
2214     // "this" should be the larger one if appropriate.
2215     BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
2216         --n;
2217         var i = r.t = this.t + a.t - n;
2218         r.s = 0; // assumes a,this >= 0
2219         while (--i >= 0) {
2220             r[i] = 0;
2221         }
2222         for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
2223             r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
2224         }
2225         r.clamp();
2226         r.drShiftTo(1, r);
2227     };
2228     // BigInteger.prototype.modInt = bnpModInt;
2229     // (protected) this % n, n < 2^26
2230     BigInteger.prototype.modInt = function (n) {
2231         if (n <= 0) {
2232             return 0;
2233         }
2234         var d = this.DV % n;
2235         var r = (this.s < 0) ? n - 1 : 0;
2236         if (this.t > 0) {
2237             if (d == 0) {
2238                 r = this[0] % n;
2239             }
2240             else {
2241                 for (var i = this.t - 1; i >= 0; --i) {
2242                     r = (d * r + this[i]) % n;
2243                 }
2244             }
2245         }
2246         return r;
2247     };
2248     // BigInteger.prototype.millerRabin = bnpMillerRabin;
2249     // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
2250     BigInteger.prototype.millerRabin = function (t) {
2251         var n1 = this.subtract(BigInteger.ONE);
2252         var k = n1.getLowestSetBit();
2253         if (k <= 0) {
2254             return false;
2255         }
2256         var r = n1.shiftRight(k);
2257         t = (t + 1) >> 1;
2258         if (t > lowprimes.length) {
2259             t = lowprimes.length;
2260         }
2261         var a = nbi();
2262         for (var i = 0; i < t; ++i) {
2263             // Pick bases at random, instead of starting at 2
2264             a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
2265             var y = a.modPow(r, this);
2266             if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
2267                 var j = 1;
2268                 while (j++ < k && y.compareTo(n1) != 0) {
2269                     y = y.modPowInt(2, this);
2270                     if (y.compareTo(BigInteger.ONE) == 0) {
2271                         return false;
2272                     }
2273                 }
2274                 if (y.compareTo(n1) != 0) {
2275                     return false;
2276                 }
2277             }
2278         }
2279         return true;
2280     };
2281     // BigInteger.prototype.square = bnSquare;
2282     // (public) this^2
2283     BigInteger.prototype.square = function () {
2284         var r = nbi();
2285         this.squareTo(r);
2286         return r;
2287     };
2288     //#region ASYNC
2289     // Public API method
2290     BigInteger.prototype.gcda = function (a, callback) {
2291         var x = (this.s < 0) ? this.negate() : this.clone();
2292         var y = (a.s < 0) ? a.negate() : a.clone();
2293         if (x.compareTo(y) < 0) {
2294             var t = x;
2295             x = y;
2296             y = t;
2297         }
2298         var i = x.getLowestSetBit();
2299         var g = y.getLowestSetBit();
2300         if (g < 0) {
2301             callback(x);
2302             return;
2303         }
2304         if (i < g) {
2305             g = i;
2306         }
2307         if (g > 0) {
2308             x.rShiftTo(g, x);
2309             y.rShiftTo(g, y);
2310         }
2311         // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
2312         var gcda1 = function () {
2313             if ((i = x.getLowestSetBit()) > 0) {
2314                 x.rShiftTo(i, x);
2315             }
2316             if ((i = y.getLowestSetBit()) > 0) {
2317                 y.rShiftTo(i, y);
2318             }
2319             if (x.compareTo(y) >= 0) {
2320                 x.subTo(y, x);
2321                 x.rShiftTo(1, x);
2322             }
2323             else {
2324                 y.subTo(x, y);
2325                 y.rShiftTo(1, y);
2326             }
2327             if (!(x.signum() > 0)) {
2328                 if (g > 0) {
2329                     y.lShiftTo(g, y);
2330                 }
2331                 setTimeout(function () { callback(y); }, 0); // escape
2332             }
2333             else {
2334                 setTimeout(gcda1, 0);
2335             }
2336         };
2337         setTimeout(gcda1, 10);
2338     };
2339     // (protected) alternate constructor
2340     BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
2341         if ("number" == typeof b) {
2342             if (a < 2) {
2343                 this.fromInt(1);
2344             }
2345             else {
2346                 this.fromNumber(a, c);
2347                 if (!this.testBit(a - 1)) {
2348                     this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2349                 }
2350                 if (this.isEven()) {
2351                     this.dAddOffset(1, 0);
2352                 }
2353                 var bnp_1 = this;
2354                 var bnpfn1_1 = function () {
2355                     bnp_1.dAddOffset(2, 0);
2356                     if (bnp_1.bitLength() > a) {
2357                         bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
2358                     }
2359                     if (bnp_1.isProbablePrime(b)) {
2360                         setTimeout(function () { callback(); }, 0); // escape
2361                     }
2362                     else {
2363                         setTimeout(bnpfn1_1, 0);
2364                     }
2365                 };
2366                 setTimeout(bnpfn1_1, 0);
2367             }
2368         }
2369         else {
2370             var x = [];
2371             var t = a & 7;
2372             x.length = (a >> 3) + 1;
2373             b.nextBytes(x);
2374             if (t > 0) {
2375                 x[0] &= ((1 << t) - 1);
2376             }
2377             else {
2378                 x[0] = 0;
2379             }
2380             this.fromString(x, 256);
2381         }
2382     };
2383     return BigInteger;
2384 }());
2385 //#region REDUCERS
2386 //#region NullExp
2387 var NullExp = /** @class */ (function () {
2388     function NullExp() {
2389     }
2390     // NullExp.prototype.convert = nNop;
2391     NullExp.prototype.convert = function (x) {
2392         return x;
2393     };
2394     // NullExp.prototype.revert = nNop;
2395     NullExp.prototype.revert = function (x) {
2396         return x;
2397     };
2398     // NullExp.prototype.mulTo = nMulTo;
2399     NullExp.prototype.mulTo = function (x, y, r) {
2400         x.multiplyTo(y, r);
2401     };
2402     // NullExp.prototype.sqrTo = nSqrTo;
2403     NullExp.prototype.sqrTo = function (x, r) {
2404         x.squareTo(r);
2405     };
2406     return NullExp;
2407 }());
2408 // Modular reduction using "classic" algorithm
2409 var Classic = /** @class */ (function () {
2410     function Classic(m) {
2411         this.m = m;
2412     }
2413     // Classic.prototype.convert = cConvert;
2414     Classic.prototype.convert = function (x) {
2415         if (x.s < 0 || x.compareTo(this.m) >= 0) {
2416             return x.mod(this.m);
2417         }
2418         else {
2419             return x;
2420         }
2421     };
2422     // Classic.prototype.revert = cRevert;
2423     Classic.prototype.revert = function (x) {
2424         return x;
2425     };
2426     // Classic.prototype.reduce = cReduce;
2427     Classic.prototype.reduce = function (x) {
2428         x.divRemTo(this.m, null, x);
2429     };
2430     // Classic.prototype.mulTo = cMulTo;
2431     Classic.prototype.mulTo = function (x, y, r) {
2432         x.multiplyTo(y, r);
2433         this.reduce(r);
2434     };
2435     // Classic.prototype.sqrTo = cSqrTo;
2436     Classic.prototype.sqrTo = function (x, r) {
2437         x.squareTo(r);
2438         this.reduce(r);
2439     };
2440     return Classic;
2441 }());
2442 //#endregion
2443 //#region Montgomery
2444 // Montgomery reduction
2445 var Montgomery = /** @class */ (function () {
2446     function Montgomery(m) {
2447         this.m = m;
2448         this.mp = m.invDigit();
2449         this.mpl = this.mp & 0x7fff;
2450         this.mph = this.mp >> 15;
2451         this.um = (1 << (m.DB - 15)) - 1;
2452         this.mt2 = 2 * m.t;
2453     }
2454     // Montgomery.prototype.convert = montConvert;
2455     // xR mod m
2456     Montgomery.prototype.convert = function (x) {
2457         var r = nbi();
2458         x.abs().dlShiftTo(this.m.t, r);
2459         r.divRemTo(this.m, null, r);
2460         if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
2461             this.m.subTo(r, r);
2462         }
2463         return r;
2464     };
2465     // Montgomery.prototype.revert = montRevert;
2466     // x/R mod m
2467     Montgomery.prototype.revert = function (x) {
2468         var r = nbi();
2469         x.copyTo(r);
2470         this.reduce(r);
2471         return r;
2472     };
2473     // Montgomery.prototype.reduce = montReduce;
2474     // x = x/R mod m (HAC 14.32)
2475     Montgomery.prototype.reduce = function (x) {
2476         while (x.t <= this.mt2) {
2477             // pad x so am has enough room later
2478             x[x.t++] = 0;
2479         }
2480         for (var i = 0; i < this.m.t; ++i) {
2481             // faster way of calculating u0 = x[i]*mp mod DV
2482             var j = x[i] & 0x7fff;
2483             var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
2484             // use am to combine the multiply-shift-add into one call
2485             j = i + this.m.t;
2486             x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
2487             // propagate carry
2488             while (x[j] >= x.DV) {
2489                 x[j] -= x.DV;
2490                 x[++j]++;
2491             }
2492         }
2493         x.clamp();
2494         x.drShiftTo(this.m.t, x);
2495         if (x.compareTo(this.m) >= 0) {
2496             x.subTo(this.m, x);
2497         }
2498     };
2499     // Montgomery.prototype.mulTo = montMulTo;
2500     // r = "xy/R mod m"; x,y != r
2501     Montgomery.prototype.mulTo = function (x, y, r) {
2502         x.multiplyTo(y, r);
2503         this.reduce(r);
2504     };
2505     // Montgomery.prototype.sqrTo = montSqrTo;
2506     // r = "x^2/R mod m"; x != r
2507     Montgomery.prototype.sqrTo = function (x, r) {
2508         x.squareTo(r);
2509         this.reduce(r);
2510     };
2511     return Montgomery;
2512 }());
2513 //#endregion Montgomery
2514 //#region Barrett
2515 // Barrett modular reduction
2516 var Barrett = /** @class */ (function () {
2517     function Barrett(m) {
2518         this.m = m;
2519         // setup Barrett
2520         this.r2 = nbi();
2521         this.q3 = nbi();
2522         BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
2523         this.mu = this.r2.divide(m);
2524     }
2525     // Barrett.prototype.convert = barrettConvert;
2526     Barrett.prototype.convert = function (x) {
2527         if (x.s < 0 || x.t > 2 * this.m.t) {
2528             return x.mod(this.m);
2529         }
2530         else if (x.compareTo(this.m) < 0) {
2531             return x;
2532         }
2533         else {
2534             var r = nbi();
2535             x.copyTo(r);
2536             this.reduce(r);
2537             return r;
2538         }
2539     };
2540     // Barrett.prototype.revert = barrettRevert;
2541     Barrett.prototype.revert = function (x) {
2542         return x;
2543     };
2544     // Barrett.prototype.reduce = barrettReduce;
2545     // x = x mod m (HAC 14.42)
2546     Barrett.prototype.reduce = function (x) {
2547         x.drShiftTo(this.m.t - 1, this.r2);
2548         if (x.t > this.m.t + 1) {
2549             x.t = this.m.t + 1;
2550             x.clamp();
2551         }
2552         this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
2553         this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
2554         while (x.compareTo(this.r2) < 0) {
2555             x.dAddOffset(1, this.m.t + 1);
2556         }
2557         x.subTo(this.r2, x);
2558         while (x.compareTo(this.m) >= 0) {
2559             x.subTo(this.m, x);
2560         }
2561     };
2562     // Barrett.prototype.mulTo = barrettMulTo;
2563     // r = x*y mod m; x,y != r
2564     Barrett.prototype.mulTo = function (x, y, r) {
2565         x.multiplyTo(y, r);
2566         this.reduce(r);
2567     };
2568     // Barrett.prototype.sqrTo = barrettSqrTo;
2569     // r = x^2 mod m; x != r
2570     Barrett.prototype.sqrTo = function (x, r) {
2571         x.squareTo(r);
2572         this.reduce(r);
2573     };
2574     return Barrett;
2575 }());
2576 //#endregion
2577 //#endregion REDUCERS
2578 // return new, unset BigInteger
2579 function nbi() { return new BigInteger(null); }
2580 function parseBigInt(str, r) {
2581     return new BigInteger(str, r);
2582 }
2583 // am: Compute w_j += (x*this_i), propagate carries,
2584 // c is initial carry, returns final carry.
2585 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
2586 // We need to select the fastest one that works in this environment.
2587 // am1: use a single mult and divide to get the high bits,
2588 // max digit bits should be 26 because
2589 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
2590 function am1(i, x, w, j, c, n) {
2591     while (--n >= 0) {
2592         var v = x * this[i++] + w[j] + c;
2593         c = Math.floor(v / 0x4000000);
2594         w[j++] = v & 0x3ffffff;
2595     }
2596     return c;
2597 }
2598 // am2 avoids a big mult-and-extract completely.
2599 // Max digit bits should be <= 30 because we do bitwise ops
2600 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
2601 function am2(i, x, w, j, c, n) {
2602     var xl = x & 0x7fff;
2603     var xh = x >> 15;
2604     while (--n >= 0) {
2605         var l = this[i] & 0x7fff;
2606         var h = this[i++] >> 15;
2607         var m = xh * l + h * xl;
2608         l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
2609         c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
2610         w[j++] = l & 0x3fffffff;
2611     }
2612     return c;
2613 }
2614 // Alternately, set max digit bits to 28 since some
2615 // browsers slow down when dealing with 32-bit numbers.
2616 function am3(i, x, w, j, c, n) {
2617     var xl = x & 0x3fff;
2618     var xh = x >> 14;
2619     while (--n >= 0) {
2620         var l = this[i] & 0x3fff;
2621         var h = this[i++] >> 14;
2622         var m = xh * l + h * xl;
2623         l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
2624         c = (l >> 28) + (m >> 14) + xh * h;
2625         w[j++] = l & 0xfffffff;
2626     }
2627     return c;
2628 }
2629 // if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
2630 //     BigInteger.prototype.am = am2;
2631 //     dbits = 30;
2632 // }
2633 // else if (j_lm && (navigator.appName != "Netscape")) {
2634 //     BigInteger.prototype.am = am1;
2635 //     dbits = 26;
2636 // }
2637 // else { // Mozilla/Netscape seems to prefer am3
2638 //     BigInteger.prototype.am = am3;
2639 //     dbits = 28;
2640 // }
2641 BigInteger.prototype.am = am1;
2642 dbits = 26;
2643
2644 BigInteger.prototype.DB = dbits;
2645 BigInteger.prototype.DM = ((1 << dbits) - 1);
2646 BigInteger.prototype.DV = (1 << dbits);
2647 var BI_FP = 52;
2648 BigInteger.prototype.FV = Math.pow(2, BI_FP);
2649 BigInteger.prototype.F1 = BI_FP - dbits;
2650 BigInteger.prototype.F2 = 2 * dbits - BI_FP;
2651 // Digit conversions
2652 var BI_RC = [];
2653 var rr;
2654 var vv;
2655 rr = "0".charCodeAt(0);
2656 for (vv = 0; vv <= 9; ++vv) {
2657     BI_RC[rr++] = vv;
2658 }
2659 rr = "a".charCodeAt(0);
2660 for (vv = 10; vv < 36; ++vv) {
2661     BI_RC[rr++] = vv;
2662 }
2663 rr = "A".charCodeAt(0);
2664 for (vv = 10; vv < 36; ++vv) {
2665     BI_RC[rr++] = vv;
2666 }
2667 function intAt(s, i) {
2668     var c = BI_RC[s.charCodeAt(i)];
2669     return (c == null) ? -1 : c;
2670 }
2671 // return bigint initialized to value
2672 function nbv(i) {
2673     var r = nbi();
2674     r.fromInt(i);
2675     return r;
2676 }
2677 // returns bit length of the integer x
2678 function nbits(x) {
2679     var r = 1;
2680     var t;
2681     if ((t = x >>> 16) != 0) {
2682         x = t;
2683         r += 16;
2684     }
2685     if ((t = x >> 8) != 0) {
2686         x = t;
2687         r += 8;
2688     }
2689     if ((t = x >> 4) != 0) {
2690         x = t;
2691         r += 4;
2692     }
2693     if ((t = x >> 2) != 0) {
2694         x = t;
2695         r += 2;
2696     }
2697     if ((t = x >> 1) != 0) {
2698         x = t;
2699         r += 1;
2700     }
2701     return r;
2702 }
2703 // "constants"
2704 BigInteger.ZERO = nbv(0);
2705 BigInteger.ONE = nbv(1);
2706
2707 // prng4.js - uses Arcfour as a PRNG
2708 var Arcfour = /** @class */ (function () {
2709     function Arcfour() {
2710         this.i = 0;
2711         this.j = 0;
2712         this.S = [];
2713     }
2714     // Arcfour.prototype.init = ARC4init;
2715     // Initialize arcfour context from key, an array of ints, each from [0..255]
2716     Arcfour.prototype.init = function (key) {
2717         var i;
2718         var j;
2719         var t;
2720         for (i = 0; i < 256; ++i) {
2721             this.S[i] = i;
2722         }
2723         j = 0;
2724         for (i = 0; i < 256; ++i) {
2725             j = (j + this.S[i] + key[i % key.length]) & 255;
2726             t = this.S[i];
2727             this.S[i] = this.S[j];
2728             this.S[j] = t;
2729         }
2730         this.i = 0;
2731         this.j = 0;
2732     };
2733     // Arcfour.prototype.next = ARC4next;
2734     Arcfour.prototype.next = function () {
2735         var t;
2736         this.i = (this.i + 1) & 255;
2737         this.j = (this.j + this.S[this.i]) & 255;
2738         t = this.S[this.i];
2739         this.S[this.i] = this.S[this.j];
2740         this.S[this.j] = t;
2741         return this.S[(t + this.S[this.i]) & 255];
2742     };
2743     return Arcfour;
2744 }());
2745 // Plug in your RNG constructor here
2746 function prng_newstate() {
2747     return new Arcfour();
2748 }
2749 // Pool size must be a multiple of 4 and greater than 32.
2750 // An array of bytes the size of the pool will be passed to init()
2751 var rng_psize = 256;
2752
2753 // Random number generator - requires a PRNG backend, e.g. prng4.js
2754 var rng_state;
2755 var rng_pool = null;
2756 var rng_pptr;
2757 // Initialize the pool with junk if needed.
2758 if (rng_pool == null) {
2759     rng_pool = [];
2760     rng_pptr = 0;
2761     var t = void 0;
2762     if (window.crypto && window.crypto.getRandomValues) {
2763         // Extract entropy (2048 bits) from RNG if available
2764         var z = new Uint32Array(256);
2765         window.crypto.getRandomValues(z);
2766         for (t = 0; t < z.length; ++t) {
2767             rng_pool[rng_pptr++] = z[t] & 255;
2768         }
2769     }
2770     // Use mouse events for entropy, if we do not have enough entropy by the time
2771     // we need it, entropy will be generated by Math.random.
2772     var onMouseMoveListener_1 = function (ev) {
2773         this.count = this.count || 0;
2774         if (this.count >= 256 || rng_pptr >= rng_psize) {
2775             if (window.removeEventListener) {
2776                 window.removeEventListener("mousemove", onMouseMoveListener_1, false);
2777             }
2778             else if (window.detachEvent) {
2779                 window.detachEvent("onmousemove", onMouseMoveListener_1);
2780             }
2781             return;
2782         }
2783         try {
2784             var mouseCoordinates = ev.x + ev.y;
2785             rng_pool[rng_pptr++] = mouseCoordinates & 255;
2786             this.count += 1;
2787         }
2788         catch (e) {
2789             // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
2790         }
2791     };
2792     if (window.addEventListener) {
2793         window.addEventListener("mousemove", onMouseMoveListener_1, false);
2794     }
2795     else if (window.attachEvent) {
2796         window.attachEvent("onmousemove", onMouseMoveListener_1);
2797     }
2798 }
2799 function rng_get_byte() {
2800     if (rng_state == null) {
2801         rng_state = prng_newstate();
2802         // At this point, we may not have collected enough entropy.  If not, fall back to Math.random
2803         while (rng_pptr < rng_psize) {
2804             var random = Math.floor(65536 * Math.random());
2805             rng_pool[rng_pptr++] = random & 255;
2806         }
2807         rng_state.init(rng_pool);
2808         for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
2809             rng_pool[rng_pptr] = 0;
2810         }
2811         rng_pptr = 0;
2812     }
2813     // TODO: allow reseeding after first request
2814     return rng_state.next();
2815 }
2816 var SecureRandom = /** @class */ (function () {
2817     function SecureRandom() {
2818     }
2819     SecureRandom.prototype.nextBytes = function (ba) {
2820         for (var i = 0; i < ba.length; ++i) {
2821             ba[i] = rng_get_byte();
2822         }
2823     };
2824     return SecureRandom;
2825 }());
2826
2827 // Depends on jsbn.js and rng.js
2828 // function linebrk(s,n) {
2829 //   var ret = "";
2830 //   var i = 0;
2831 //   while(i + n < s.length) {
2832 //     ret += s.substring(i,i+n) + "\n";
2833 //     i += n;
2834 //   }
2835 //   return ret + s.substring(i,s.length);
2836 // }
2837 // function byte2Hex(b) {
2838 //   if(b < 0x10)
2839 //     return "0" + b.toString(16);
2840 //   else
2841 //     return b.toString(16);
2842 // }
2843 function pkcs1pad1(s, n) {
2844     if (n < s.length + 22) {
2845         console.error("Message too long for RSA");
2846         return null;
2847     }
2848     var len = n - s.length - 6;
2849     var filler = "";
2850     for (var f = 0; f < len; f += 2) {
2851         filler += "ff";
2852     }
2853     var m = "0001" + filler + "00" + s;
2854     return parseBigInt(m, 16);
2855 }
2856 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
2857 function pkcs1pad2(s, n) {
2858     if (n < s.length + 11) { // TODO: fix for utf-8
2859         console.error("Message too long for RSA");
2860         return null;
2861     }
2862     var ba = [];
2863     var i = s.length - 1;
2864     while (i >= 0 && n > 0) {
2865         var c = s.charCodeAt(i--);
2866         if (c < 128) { // encode using utf-8
2867             ba[--n] = c;
2868         }
2869         else if ((c > 127) && (c < 2048)) {
2870             ba[--n] = (c & 63) | 128;
2871             ba[--n] = (c >> 6) | 192;
2872         }
2873         else {
2874             ba[--n] = (c & 63) | 128;
2875             ba[--n] = ((c >> 6) & 63) | 128;
2876             ba[--n] = (c >> 12) | 224;
2877         }
2878     }
2879     ba[--n] = 0;
2880     var rng = new SecureRandom();
2881     var x = [];
2882     while (n > 2) { // random non-zero pad
2883         x[0] = 0;
2884         while (x[0] == 0) {
2885             rng.nextBytes(x);
2886         }
2887         ba[--n] = x[0];
2888     }
2889     ba[--n] = 2;
2890     ba[--n] = 0;
2891     return new BigInteger(ba);
2892 }
2893 // "empty" RSA key constructor
2894 var RSAKey = /** @class */ (function () {
2895     function RSAKey() {
2896         this.n = null;
2897         this.e = 0;
2898         this.d = null;
2899         this.p = null;
2900         this.q = null;
2901         this.dmp1 = null;
2902         this.dmq1 = null;
2903         this.coeff = null;
2904     }
2905     //#region PROTECTED
2906     // protected
2907     // RSAKey.prototype.doPublic = RSADoPublic;
2908     // Perform raw public operation on "x": return x^e (mod n)
2909     RSAKey.prototype.doPublic = function (x) {
2910         return x.modPowInt(this.e, this.n);
2911     };
2912     // RSAKey.prototype.doPrivate = RSADoPrivate;
2913     // Perform raw private operation on "x": return x^d (mod n)
2914     RSAKey.prototype.doPrivate = function (x) {
2915         if (this.p == null || this.q == null) {
2916             return x.modPow(this.d, this.n);
2917         }
2918         // TODO: re-calculate any missing CRT params
2919         var xp = x.mod(this.p).modPow(this.dmp1, this.p);
2920         var xq = x.mod(this.q).modPow(this.dmq1, this.q);
2921         while (xp.compareTo(xq) < 0) {
2922             xp = xp.add(this.p);
2923         }
2924         return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
2925     };
2926     //#endregion PROTECTED
2927     //#region PUBLIC
2928     // RSAKey.prototype.setPublic = RSASetPublic;
2929     // Set the public key fields N and e from hex strings
2930     RSAKey.prototype.setPublic = function (N, E) {
2931         if (N != null && E != null && N.length > 0 && E.length > 0) {
2932             this.n = parseBigInt(N, 16);
2933             this.e = parseInt(E, 16);
2934         }
2935         else {
2936             console.error("Invalid RSA public key");
2937         }
2938     };
2939     // RSAKey.prototype.encrypt = RSAEncrypt;
2940     // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
2941     RSAKey.prototype.encrypt = function (text) {
2942         var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
2943         if (m == null) {
2944             return null;
2945         }
2946         var c = this.doPublic(m);
2947         if (c == null) {
2948             return null;
2949         }
2950         var h = c.toString(16);
2951         if ((h.length & 1) == 0) {
2952             return h;
2953         }
2954         else {
2955             return "0" + h;
2956         }
2957     };
2958     // RSAKey.prototype.setPrivate = RSASetPrivate;
2959     // Set the private key fields N, e, and d from hex strings
2960     RSAKey.prototype.setPrivate = function (N, E, D) {
2961         if (N != null && E != null && N.length > 0 && E.length > 0) {
2962             this.n = parseBigInt(N, 16);
2963             this.e = parseInt(E, 16);
2964             this.d = parseBigInt(D, 16);
2965         }
2966         else {
2967             console.error("Invalid RSA private key");
2968         }
2969     };
2970     // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
2971     // Set the private key fields N, e, d and CRT params from hex strings
2972     RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
2973         if (N != null && E != null && N.length > 0 && E.length > 0) {
2974             this.n = parseBigInt(N, 16);
2975             this.e = parseInt(E, 16);
2976             this.d = parseBigInt(D, 16);
2977             this.p = parseBigInt(P, 16);
2978             this.q = parseBigInt(Q, 16);
2979             this.dmp1 = parseBigInt(DP, 16);
2980             this.dmq1 = parseBigInt(DQ, 16);
2981             this.coeff = parseBigInt(C, 16);
2982         }
2983         else {
2984             console.error("Invalid RSA private key");
2985         }
2986     };
2987     // RSAKey.prototype.generate = RSAGenerate;
2988     // Generate a new random private key B bits long, using public expt E
2989     RSAKey.prototype.generate = function (B, E) {
2990         var rng = new SecureRandom();
2991         var qs = B >> 1;
2992         this.e = parseInt(E, 16);
2993         var ee = new BigInteger(E, 16);
2994         for (;;) {
2995             for (;;) {
2996                 this.p = new BigInteger(B - qs, 1, rng);
2997                 if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
2998                     break;
2999                 }
3000             }
3001             for (;;) {
3002                 this.q = new BigInteger(qs, 1, rng);
3003                 if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
3004                     break;
3005                 }
3006             }
3007             if (this.p.compareTo(this.q) <= 0) {
3008                 var t = this.p;
3009                 this.p = this.q;
3010                 this.q = t;
3011             }
3012             var p1 = this.p.subtract(BigInteger.ONE);
3013             var q1 = this.q.subtract(BigInteger.ONE);
3014             var phi = p1.multiply(q1);
3015             if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3016                 this.n = this.p.multiply(this.q);
3017                 this.d = ee.modInverse(phi);
3018                 this.dmp1 = this.d.mod(p1);
3019                 this.dmq1 = this.d.mod(q1);
3020                 this.coeff = this.q.modInverse(this.p);
3021                 break;
3022             }
3023         }
3024     };
3025     // RSAKey.prototype.decrypt = RSADecrypt;
3026     // Return the PKCS#1 RSA decryption of "ctext".
3027     // "ctext" is an even-length hex string and the output is a plain string.
3028     RSAKey.prototype.decrypt = function (ctext) {
3029         var c = parseBigInt(ctext, 16);
3030         var m = this.doPrivate(c);
3031         if (m == null) {
3032             return null;
3033         }
3034         return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
3035     };
3036     // Generate a new random private key B bits long, using public expt E
3037     RSAKey.prototype.generateAsync = function (B, E, callback) {
3038         var rng = new SecureRandom();
3039         var qs = B >> 1;
3040         this.e = parseInt(E, 16);
3041         var ee = new BigInteger(E, 16);
3042         var rsa = this;
3043         // These functions have non-descript names because they were originally for(;;) loops.
3044         // I don't know about cryptography to give them better names than loop1-4.
3045         var loop1 = function () {
3046             var loop4 = function () {
3047                 if (rsa.p.compareTo(rsa.q) <= 0) {
3048                     var t = rsa.p;
3049                     rsa.p = rsa.q;
3050                     rsa.q = t;
3051                 }
3052                 var p1 = rsa.p.subtract(BigInteger.ONE);
3053                 var q1 = rsa.q.subtract(BigInteger.ONE);
3054                 var phi = p1.multiply(q1);
3055                 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3056                     rsa.n = rsa.p.multiply(rsa.q);
3057                     rsa.d = ee.modInverse(phi);
3058                     rsa.dmp1 = rsa.d.mod(p1);
3059                     rsa.dmq1 = rsa.d.mod(q1);
3060                     rsa.coeff = rsa.q.modInverse(rsa.p);
3061                     setTimeout(function () { callback(); }, 0); // escape
3062                 }
3063                 else {
3064                     setTimeout(loop1, 0);
3065                 }
3066             };
3067             var loop3 = function () {
3068                 rsa.q = nbi();
3069                 rsa.q.fromNumberAsync(qs, 1, rng, function () {
3070                     rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
3071                         if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
3072                             setTimeout(loop4, 0);
3073                         }
3074                         else {
3075                             setTimeout(loop3, 0);
3076                         }
3077                     });
3078                 });
3079             };
3080             var loop2 = function () {
3081                 rsa.p = nbi();
3082                 rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
3083                     rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
3084                         if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
3085                             setTimeout(loop3, 0);
3086                         }
3087                         else {
3088                             setTimeout(loop2, 0);
3089                         }
3090                     });
3091                 });
3092             };
3093             setTimeout(loop2, 0);
3094         };
3095         setTimeout(loop1, 0);
3096     };
3097     RSAKey.prototype.sign = function (text, digestMethod, digestName) {
3098         var header = getDigestHeader(digestName);
3099         var digest = header + digestMethod(text).toString();
3100         var m = pkcs1pad1(digest, this.n.bitLength() / 4);
3101         if (m == null) {
3102             return null;
3103         }
3104         var c = this.doPrivate(m);
3105         if (c == null) {
3106             return null;
3107         }
3108         var h = c.toString(16);
3109         if ((h.length & 1) == 0) {
3110             return h;
3111         }
3112         else {
3113             return "0" + h;
3114         }
3115     };
3116     RSAKey.prototype.verify = function (text, signature, digestMethod) {
3117         var c = parseBigInt(signature, 16);
3118         var m = this.doPublic(c);
3119         if (m == null) {
3120             return null;
3121         }
3122         var unpadded = m.toString(16).replace(/^1f+00/, "");
3123         var digest = removeDigestHeader(unpadded);
3124         return digest == digestMethod(text).toString();
3125     };
3126     return RSAKey;
3127 }());
3128 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
3129 function pkcs1unpad2(d, n) {
3130     var b = d.toByteArray();
3131     var i = 0;
3132     while (i < b.length && b[i] == 0) {
3133         ++i;
3134     }
3135     if (b.length - i != n - 1 || b[i] != 2) {
3136         return null;
3137     }
3138     ++i;
3139     while (b[i] != 0) {
3140         if (++i >= b.length) {
3141             return null;
3142         }
3143     }
3144     var ret = "";
3145     while (++i < b.length) {
3146         var c = b[i] & 255;
3147         if (c < 128) { // utf-8 decode
3148             ret += String.fromCharCode(c);
3149         }
3150         else if ((c > 191) && (c < 224)) {
3151             ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
3152             ++i;
3153         }
3154         else {
3155             ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
3156             i += 2;
3157         }
3158     }
3159     return ret;
3160 }
3161 // https://tools.ietf.org/html/rfc3447#page-43
3162 var DIGEST_HEADERS = {
3163     md2: "3020300c06082a864886f70d020205000410",
3164     md5: "3020300c06082a864886f70d020505000410",
3165     sha1: "3021300906052b0e03021a05000414",
3166     sha224: "302d300d06096086480165030402040500041c",
3167     sha256: "3031300d060960864801650304020105000420",
3168     sha384: "3041300d060960864801650304020205000430",
3169     sha512: "3051300d060960864801650304020305000440",
3170     ripemd160: "3021300906052b2403020105000414",
3171 };
3172 function getDigestHeader(name) {
3173     return DIGEST_HEADERS[name] || "";
3174 }
3175 function removeDigestHeader(str) {
3176     for (var name_1 in DIGEST_HEADERS) {
3177         if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
3178             var header = DIGEST_HEADERS[name_1];
3179             var len = header.length;
3180             if (str.substr(0, len) == header) {
3181                 return str.substr(len);
3182             }
3183         }
3184     }
3185     return str;
3186 }
3187 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
3188 // function RSAEncryptB64(text) {
3189 //  var h = this.encrypt(text);
3190 //  if(h) return hex2b64(h); else return null;
3191 // }
3192 // public
3193 // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
3194
3195 /*!
3196 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3197 Code licensed under the BSD License:
3198 http://developer.yahoo.com/yui/license.html
3199 version: 2.9.0
3200 */
3201 var YAHOO = {};
3202 YAHOO.lang = {
3203     /**
3204      * Utility to set up the prototype, constructor and superclass properties to
3205      * support an inheritance strategy that can chain constructors and methods.
3206      * Static members will not be inherited.
3207      *
3208      * @method extend
3209      * @static
3210      * @param {Function} subc   the object to modify
3211      * @param {Function} superc the object to inherit
3212      * @param {Object} overrides  additional properties/methods to add to the
3213      *                              subclass prototype.  These will override the
3214      *                              matching items obtained from the superclass
3215      *                              if present.
3216      */
3217     extend: function(subc, superc, overrides) {
3218         if (! superc || ! subc) {
3219             throw new Error("YAHOO.lang.extend failed, please check that " +
3220                 "all dependencies are included.");
3221         }
3222
3223         var F = function() {};
3224         F.prototype = superc.prototype;
3225         subc.prototype = new F();
3226         subc.prototype.constructor = subc;
3227         subc.superclass = superc.prototype;
3228
3229         if (superc.prototype.constructor == Object.prototype.constructor) {
3230             superc.prototype.constructor = superc;
3231         }
3232
3233         if (overrides) {
3234             var i;
3235             for (i in overrides) {
3236                 subc.prototype[i] = overrides[i];
3237             }
3238
3239             /*
3240              * IE will not enumerate native functions in a derived object even if the
3241              * function was overridden.  This is a workaround for specific functions
3242              * we care about on the Object prototype.
3243              * @property _IEEnumFix
3244              * @param {Function} r  the object to receive the augmentation
3245              * @param {Function} s  the object that supplies the properties to augment
3246              * @static
3247              * @private
3248              */
3249             var _IEEnumFix = function() {},
3250                 ADD = ["toString", "valueOf"];
3251             try {
3252                 if (/MSIE/.test(navigator.userAgent)) {
3253                     _IEEnumFix = function(r, s) {
3254                         for (i = 0; i < ADD.length; i = i + 1) {
3255                             var fname = ADD[i], f = s[fname];
3256                             if (typeof f === 'function' && f != Object.prototype[fname]) {
3257                                 r[fname] = f;
3258                             }
3259                         }
3260                     };
3261                 }
3262             } catch (ex) {}            _IEEnumFix(subc.prototype, overrides);
3263         }
3264     }
3265 };
3266
3267 /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
3268  */
3269
3270 /**
3271  * @fileOverview
3272  * @name asn1-1.0.js
3273  * @author Kenji Urushima kenji.urushima@gmail.com
3274  * @version asn1 1.0.13 (2017-Jun-02)
3275  * @since jsrsasign 2.1
3276  * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
3277  */
3278
3279 /**
3280  * kjur's class library name space
3281  * <p>
3282  * This name space provides following name spaces:
3283  * <ul>
3284  * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
3285  * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
3286  * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
3287  * class and utilities</li>
3288  * </ul>
3289  * </p>
3290  * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
3291  * @name KJUR
3292  * @namespace kjur's class library name space
3293  */
3294 var KJUR = {};
3295
3296 /**
3297  * kjur's ASN.1 class library name space
3298  * <p>
3299  * This is ITU-T X.690 ASN.1 DER encoder class library and
3300  * class structure and methods is very similar to
3301  * org.bouncycastle.asn1 package of
3302  * well known BouncyCaslte Cryptography Library.
3303  * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
3304  * Here are ASN.1 DER primitive classes.
3305  * <ul>
3306  * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
3307  * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
3308  * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
3309  * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
3310  * <li>0x05 {@link KJUR.asn1.DERNull}</li>
3311  * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
3312  * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
3313  * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
3314  * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
3315  * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
3316  * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
3317  * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
3318  * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
3319  * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
3320  * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
3321  * <li>0x31 {@link KJUR.asn1.DERSet}</li>
3322  * </ul>
3323  * <h4>OTHER ASN.1 CLASSES</h4>
3324  * <ul>
3325  * <li>{@link KJUR.asn1.ASN1Object}</li>
3326  * <li>{@link KJUR.asn1.DERAbstractString}</li>
3327  * <li>{@link KJUR.asn1.DERAbstractTime}</li>
3328  * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
3329  * <li>{@link KJUR.asn1.DERTaggedObject}</li>
3330  * </ul>
3331  * <h4>SUB NAME SPACES</h4>
3332  * <ul>
3333  * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
3334  * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
3335  * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
3336  * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
3337  * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
3338  * </ul>
3339  * </p>
3340  * NOTE: Please ignore method summary and document of this namespace.
3341  * This caused by a bug of jsdoc2.
3342  * @name KJUR.asn1
3343  * @namespace
3344  */
3345 if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
3346
3347 /**
3348  * ASN1 utilities class
3349  * @name KJUR.asn1.ASN1Util
3350  * @class ASN1 utilities class
3351  * @since asn1 1.0.2
3352  */
3353 KJUR.asn1.ASN1Util = new function() {
3354     this.integerToByteHex = function(i) {
3355         var h = i.toString(16);
3356         if ((h.length % 2) == 1) h = '0' + h;
3357         return h;
3358     };
3359     this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
3360         var h = bigIntegerValue.toString(16);
3361         if (h.substr(0, 1) != '-') {
3362             if (h.length % 2 == 1) {
3363                 h = '0' + h;
3364             } else {
3365                 if (! h.match(/^[0-7]/)) {
3366                     h = '00' + h;
3367                 }
3368             }
3369         } else {
3370             var hPos = h.substr(1);
3371             var xorLen = hPos.length;
3372             if (xorLen % 2 == 1) {
3373                 xorLen += 1;
3374             } else {
3375                 if (! h.match(/^[0-7]/)) {
3376                     xorLen += 2;
3377                 }
3378             }
3379             var hMask = '';
3380             for (var i = 0; i < xorLen; i++) {
3381                 hMask += 'f';
3382             }
3383             var biMask = new BigInteger(hMask, 16);
3384             var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
3385             h = biNeg.toString(16).replace(/^-/, '');
3386         }
3387         return h;
3388     };
3389     /**
3390      * get PEM string from hexadecimal data and header string
3391      * @name getPEMStringFromHex
3392      * @memberOf KJUR.asn1.ASN1Util
3393      * @function
3394      * @param {String} dataHex hexadecimal string of PEM body
3395      * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
3396      * @return {String} PEM formatted string of input data
3397      * @description
3398      * This method converts a hexadecimal string to a PEM string with
3399      * a specified header. Its line break will be CRLF("\r\n").
3400      * @example
3401      * var pem  = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
3402      * // value of pem will be:
3403      * -----BEGIN PRIVATE KEY-----
3404      * YWFh
3405      * -----END PRIVATE KEY-----
3406      */
3407     this.getPEMStringFromHex = function(dataHex, pemHeader) {
3408         return hextopem(dataHex, pemHeader);
3409     };
3410
3411     /**
3412      * generate ASN1Object specifed by JSON parameters
3413      * @name newObject
3414      * @memberOf KJUR.asn1.ASN1Util
3415      * @function
3416      * @param {Array} param JSON parameter to generate ASN1Object
3417      * @return {KJUR.asn1.ASN1Object} generated object
3418      * @since asn1 1.0.3
3419      * @description
3420      * generate any ASN1Object specified by JSON param
3421      * including ASN.1 primitive or structured.
3422      * Generally 'param' can be described as follows:
3423      * <blockquote>
3424      * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
3425      * </blockquote>
3426      * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
3427      * <ul>
3428      * <li>'bool' - DERBoolean</li>
3429      * <li>'int' - DERInteger</li>
3430      * <li>'bitstr' - DERBitString</li>
3431      * <li>'octstr' - DEROctetString</li>
3432      * <li>'null' - DERNull</li>
3433      * <li>'oid' - DERObjectIdentifier</li>
3434      * <li>'enum' - DEREnumerated</li>
3435      * <li>'utf8str' - DERUTF8String</li>
3436      * <li>'numstr' - DERNumericString</li>
3437      * <li>'prnstr' - DERPrintableString</li>
3438      * <li>'telstr' - DERTeletexString</li>
3439      * <li>'ia5str' - DERIA5String</li>
3440      * <li>'utctime' - DERUTCTime</li>
3441      * <li>'gentime' - DERGeneralizedTime</li>
3442      * <li>'seq' - DERSequence</li>
3443      * <li>'set' - DERSet</li>
3444      * <li>'tag' - DERTaggedObject</li>
3445      * </ul>
3446      * @example
3447      * newObject({'prnstr': 'aaa'});
3448      * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
3449      * // ASN.1 Tagged Object
3450      * newObject({'tag': {'tag': 'a1',
3451      *                    'explicit': true,
3452      *                    'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
3453      * // more simple representation of ASN.1 Tagged Object
3454      * newObject({'tag': ['a1',
3455      *                    true,
3456      *                    {'seq': [
3457      *                      {'int': 3},
3458      *                      {'prnstr': 'aaa'}]}
3459      *                   ]});
3460      */
3461     this.newObject = function(param) {
3462         var _KJUR = KJUR,
3463             _KJUR_asn1 = _KJUR.asn1,
3464             _DERBoolean = _KJUR_asn1.DERBoolean,
3465             _DERInteger = _KJUR_asn1.DERInteger,
3466             _DERBitString = _KJUR_asn1.DERBitString,
3467             _DEROctetString = _KJUR_asn1.DEROctetString,
3468             _DERNull = _KJUR_asn1.DERNull,
3469             _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
3470             _DEREnumerated = _KJUR_asn1.DEREnumerated,
3471             _DERUTF8String = _KJUR_asn1.DERUTF8String,
3472             _DERNumericString = _KJUR_asn1.DERNumericString,
3473             _DERPrintableString = _KJUR_asn1.DERPrintableString,
3474             _DERTeletexString = _KJUR_asn1.DERTeletexString,
3475             _DERIA5String = _KJUR_asn1.DERIA5String,
3476             _DERUTCTime = _KJUR_asn1.DERUTCTime,
3477             _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
3478             _DERSequence = _KJUR_asn1.DERSequence,
3479             _DERSet = _KJUR_asn1.DERSet,
3480             _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
3481             _newObject = _KJUR_asn1.ASN1Util.newObject;
3482
3483         var keys = Object.keys(param);
3484         if (keys.length != 1)
3485             throw "key of param shall be only one.";
3486         var key = keys[0];
3487
3488         if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
3489             throw "undefined key: " + key;
3490
3491         if (key == "bool")    return new _DERBoolean(param[key]);
3492         if (key == "int")     return new _DERInteger(param[key]);
3493         if (key == "bitstr")  return new _DERBitString(param[key]);
3494         if (key == "octstr")  return new _DEROctetString(param[key]);
3495         if (key == "null")    return new _DERNull(param[key]);
3496         if (key == "oid")     return new _DERObjectIdentifier(param[key]);
3497         if (key == "enum")    return new _DEREnumerated(param[key]);
3498         if (key == "utf8str") return new _DERUTF8String(param[key]);
3499         if (key == "numstr")  return new _DERNumericString(param[key]);
3500         if (key == "prnstr")  return new _DERPrintableString(param[key]);
3501         if (key == "telstr")  return new _DERTeletexString(param[key]);
3502         if (key == "ia5str")  return new _DERIA5String(param[key]);
3503         if (key == "utctime") return new _DERUTCTime(param[key]);
3504         if (key == "gentime") return new _DERGeneralizedTime(param[key]);
3505
3506         if (key == "seq") {
3507             var paramList = param[key];
3508             var a = [];
3509             for (var i = 0; i < paramList.length; i++) {
3510                 var asn1Obj = _newObject(paramList[i]);
3511                 a.push(asn1Obj);
3512             }
3513             return new _DERSequence({'array': a});
3514         }
3515
3516         if (key == "set") {
3517             var paramList = param[key];
3518             var a = [];
3519             for (var i = 0; i < paramList.length; i++) {
3520                 var asn1Obj = _newObject(paramList[i]);
3521                 a.push(asn1Obj);
3522             }
3523             return new _DERSet({'array': a});
3524         }
3525
3526         if (key == "tag") {
3527             var tagParam = param[key];
3528             if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
3529                 tagParam.length == 3) {
3530                 var obj = _newObject(tagParam[2]);
3531                 return new _DERTaggedObject({tag: tagParam[0],
3532                     explicit: tagParam[1],
3533                     obj: obj});
3534             } else {
3535                 var newParam = {};
3536                 if (tagParam.explicit !== undefined)
3537                     newParam.explicit = tagParam.explicit;
3538                 if (tagParam.tag !== undefined)
3539                     newParam.tag = tagParam.tag;
3540                 if (tagParam.obj === undefined)
3541                     throw "obj shall be specified for 'tag'.";
3542                 newParam.obj = _newObject(tagParam.obj);
3543                 return new _DERTaggedObject(newParam);
3544             }
3545         }
3546     };
3547
3548     /**
3549      * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
3550      * @name jsonToASN1HEX
3551      * @memberOf KJUR.asn1.ASN1Util
3552      * @function
3553      * @param {Array} param JSON parameter to generate ASN1Object
3554      * @return hexadecimal string of ASN1Object
3555      * @since asn1 1.0.4
3556      * @description
3557      * As for ASN.1 object representation of JSON object,
3558      * please see {@link newObject}.
3559      * @example
3560      * jsonToASN1HEX({'prnstr': 'aaa'});
3561      */
3562     this.jsonToASN1HEX = function(param) {
3563         var asn1Obj = this.newObject(param);
3564         return asn1Obj.getEncodedHex();
3565     };
3566 };
3567
3568 /**
3569  * get dot noted oid number string from hexadecimal value of OID
3570  * @name oidHexToInt
3571  * @memberOf KJUR.asn1.ASN1Util
3572  * @function
3573  * @param {String} hex hexadecimal value of object identifier
3574  * @return {String} dot noted string of object identifier
3575  * @since jsrsasign 4.8.3 asn1 1.0.7
3576  * @description
3577  * This static method converts from hexadecimal string representation of
3578  * ASN.1 value of object identifier to oid number string.
3579  * @example
3580  * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6"
3581  */
3582 KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
3583     var s = "";
3584     var i01 = parseInt(hex.substr(0, 2), 16);
3585     var i0 = Math.floor(i01 / 40);
3586     var i1 = i01 % 40;
3587     var s = i0 + "." + i1;
3588
3589     var binbuf = "";
3590     for (var i = 2; i < hex.length; i += 2) {
3591         var value = parseInt(hex.substr(i, 2), 16);
3592         var bin = ("00000000" + value.toString(2)).slice(- 8);
3593         binbuf = binbuf + bin.substr(1, 7);
3594         if (bin.substr(0, 1) == "0") {
3595             var bi = new BigInteger(binbuf, 2);
3596             s = s + "." + bi.toString(10);
3597             binbuf = "";
3598         }
3599     }
3600     return s;
3601 };
3602
3603 /**
3604  * get hexadecimal value of object identifier from dot noted oid value
3605  * @name oidIntToHex
3606  * @memberOf KJUR.asn1.ASN1Util
3607  * @function
3608  * @param {String} oidString dot noted string of object identifier
3609  * @return {String} hexadecimal value of object identifier
3610  * @since jsrsasign 4.8.3 asn1 1.0.7
3611  * @description
3612  * This static method converts from object identifier value string.
3613  * to hexadecimal string representation of it.
3614  * @example
3615  * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406"
3616  */
3617 KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
3618     var itox = function(i) {
3619         var h = i.toString(16);
3620         if (h.length == 1) h = '0' + h;
3621         return h;
3622     };
3623
3624     var roidtox = function(roid) {
3625         var h = '';
3626         var bi = new BigInteger(roid, 10);
3627         var b = bi.toString(2);
3628         var padLen = 7 - b.length % 7;
3629         if (padLen == 7) padLen = 0;
3630         var bPad = '';
3631         for (var i = 0; i < padLen; i++) bPad += '0';
3632         b = bPad + b;
3633         for (var i = 0; i < b.length - 1; i += 7) {
3634             var b8 = b.substr(i, 7);
3635             if (i != b.length - 7) b8 = '1' + b8;
3636             h += itox(parseInt(b8, 2));
3637         }
3638         return h;
3639     };
3640
3641     if (! oidString.match(/^[0-9.]+$/)) {
3642         throw "malformed oid string: " + oidString;
3643     }
3644     var h = '';
3645     var a = oidString.split('.');
3646     var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
3647     h += itox(i0);
3648     a.splice(0, 2);
3649     for (var i = 0; i < a.length; i++) {
3650         h += roidtox(a[i]);
3651     }
3652     return h;
3653 };
3654
3655
3656 // ********************************************************************
3657 //  Abstract ASN.1 Classes
3658 // ********************************************************************
3659
3660 // ********************************************************************
3661
3662 /**
3663  * base class for ASN.1 DER encoder object
3664  * @name KJUR.asn1.ASN1Object
3665  * @class base class for ASN.1 DER encoder object
3666  * @property {Boolean} isModified flag whether internal data was changed
3667  * @property {String} hTLV hexadecimal string of ASN.1 TLV
3668  * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
3669  * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
3670  * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
3671  * @description
3672  */
3673 KJUR.asn1.ASN1Object = function() {
3674     var hV = '';
3675
3676     /**
3677      * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
3678      * @name getLengthHexFromValue
3679      * @memberOf KJUR.asn1.ASN1Object#
3680      * @function
3681      * @return {String} hexadecimal string of ASN.1 TLV length(L)
3682      */
3683     this.getLengthHexFromValue = function() {
3684         if (typeof this.hV == "undefined" || this.hV == null) {
3685             throw "this.hV is null or undefined.";
3686         }
3687         if (this.hV.length % 2 == 1) {
3688             throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
3689         }
3690         var n = this.hV.length / 2;
3691         var hN = n.toString(16);
3692         if (hN.length % 2 == 1) {
3693             hN = "0" + hN;
3694         }
3695         if (n < 128) {
3696             return hN;
3697         } else {
3698             var hNlen = hN.length / 2;
3699             if (hNlen > 15) {
3700                 throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
3701             }
3702             var head = 128 + hNlen;
3703             return head.toString(16) + hN;
3704         }
3705     };
3706
3707     /**
3708      * get hexadecimal string of ASN.1 TLV bytes
3709      * @name getEncodedHex
3710      * @memberOf KJUR.asn1.ASN1Object#
3711      * @function
3712      * @return {String} hexadecimal string of ASN.1 TLV
3713      */
3714     this.getEncodedHex = function() {
3715         if (this.hTLV == null || this.isModified) {
3716             this.hV = this.getFreshValueHex();
3717             this.hL = this.getLengthHexFromValue();
3718             this.hTLV = this.hT + this.hL + this.hV;
3719             this.isModified = false;
3720             //alert("first time: " + this.hTLV);
3721         }
3722         return this.hTLV;
3723     };
3724
3725     /**
3726      * get hexadecimal string of ASN.1 TLV value(V) bytes
3727      * @name getValueHex
3728      * @memberOf KJUR.asn1.ASN1Object#
3729      * @function
3730      * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
3731      */
3732     this.getValueHex = function() {
3733         this.getEncodedHex();
3734         return this.hV;
3735     };
3736
3737     this.getFreshValueHex = function() {
3738         return '';
3739     };
3740 };
3741
3742 // == BEGIN DERAbstractString ================================================
3743 /**
3744  * base class for ASN.1 DER string classes
3745  * @name KJUR.asn1.DERAbstractString
3746  * @class base class for ASN.1 DER string classes
3747  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
3748  * @property {String} s internal string of value
3749  * @extends KJUR.asn1.ASN1Object
3750  * @description
3751  * <br/>
3752  * As for argument 'params' for constructor, you can specify one of
3753  * following properties:
3754  * <ul>
3755  * <li>str - specify initial ASN.1 value(V) by a string</li>
3756  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
3757  * </ul>
3758  * NOTE: 'params' can be omitted.
3759  */
3760 KJUR.asn1.DERAbstractString = function(params) {
3761     KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3762
3763     /**
3764      * get string value of this string object
3765      * @name getString
3766      * @memberOf KJUR.asn1.DERAbstractString#
3767      * @function
3768      * @return {String} string value of this string object
3769      */
3770     this.getString = function() {
3771         return this.s;
3772     };
3773
3774     /**
3775      * set value by a string
3776      * @name setString
3777      * @memberOf KJUR.asn1.DERAbstractString#
3778      * @function
3779      * @param {String} newS value by a string to set
3780      */
3781     this.setString = function(newS) {
3782         this.hTLV = null;
3783         this.isModified = true;
3784         this.s = newS;
3785         this.hV = stohex(this.s);
3786     };
3787
3788     /**
3789      * set value by a hexadecimal string
3790      * @name setStringHex
3791      * @memberOf KJUR.asn1.DERAbstractString#
3792      * @function
3793      * @param {String} newHexString value by a hexadecimal string to set
3794      */
3795     this.setStringHex = function(newHexString) {
3796         this.hTLV = null;
3797         this.isModified = true;
3798         this.s = null;
3799         this.hV = newHexString;
3800     };
3801
3802     this.getFreshValueHex = function() {
3803         return this.hV;
3804     };
3805
3806     if (typeof params != "undefined") {
3807         if (typeof params == "string") {
3808             this.setString(params);
3809         } else if (typeof params['str'] != "undefined") {
3810             this.setString(params['str']);
3811         } else if (typeof params['hex'] != "undefined") {
3812             this.setStringHex(params['hex']);
3813         }
3814     }
3815 };
3816 YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
3817 // == END   DERAbstractString ================================================
3818
3819 // == BEGIN DERAbstractTime ==================================================
3820 /**
3821  * base class for ASN.1 DER Generalized/UTCTime class
3822  * @name KJUR.asn1.DERAbstractTime
3823  * @class base class for ASN.1 DER Generalized/UTCTime class
3824  * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
3825  * @extends KJUR.asn1.ASN1Object
3826  * @description
3827  * @see KJUR.asn1.ASN1Object - superclass
3828  */
3829 KJUR.asn1.DERAbstractTime = function(params) {
3830     KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
3831
3832     // --- PRIVATE METHODS --------------------
3833     this.localDateToUTC = function(d) {
3834         utc = d.getTime() + (d.getTimezoneOffset() * 60000);
3835         var utcDate = new Date(utc);
3836         return utcDate;
3837     };
3838
3839     /*
3840      * format date string by Data object
3841      * @name formatDate
3842      * @memberOf KJUR.asn1.AbstractTime;
3843      * @param {Date} dateObject
3844      * @param {string} type 'utc' or 'gen'
3845      * @param {boolean} withMillis flag for with millisections or not
3846      * @description
3847      * 'withMillis' flag is supported from asn1 1.0.6.
3848      */
3849     this.formatDate = function(dateObject, type, withMillis) {
3850         var pad = this.zeroPadding;
3851         var d = this.localDateToUTC(dateObject);
3852         var year = String(d.getFullYear());
3853         if (type == 'utc') year = year.substr(2, 2);
3854         var month = pad(String(d.getMonth() + 1), 2);
3855         var day = pad(String(d.getDate()), 2);
3856         var hour = pad(String(d.getHours()), 2);
3857         var min = pad(String(d.getMinutes()), 2);
3858         var sec = pad(String(d.getSeconds()), 2);
3859         var s = year + month + day + hour + min + sec;
3860         if (withMillis === true) {
3861             var millis = d.getMilliseconds();
3862             if (millis != 0) {
3863                 var sMillis = pad(String(millis), 3);
3864                 sMillis = sMillis.replace(/[0]+$/, "");
3865                 s = s + "." + sMillis;
3866             }
3867         }
3868         return s + "Z";
3869     };
3870
3871     this.zeroPadding = function(s, len) {
3872         if (s.length >= len) return s;
3873         return new Array(len - s.length + 1).join('0') + s;
3874     };
3875
3876     // --- PUBLIC METHODS --------------------
3877     /**
3878      * get string value of this string object
3879      * @name getString
3880      * @memberOf KJUR.asn1.DERAbstractTime#
3881      * @function
3882      * @return {String} string value of this time object
3883      */
3884     this.getString = function() {
3885         return this.s;
3886     };
3887
3888     /**
3889      * set value by a string
3890      * @name setString
3891      * @memberOf KJUR.asn1.DERAbstractTime#
3892      * @function
3893      * @param {String} newS value by a string to set such like "130430235959Z"
3894      */
3895     this.setString = function(newS) {
3896         this.hTLV = null;
3897         this.isModified = true;
3898         this.s = newS;
3899         this.hV = stohex(newS);
3900     };
3901
3902     /**
3903      * set value by a Date object
3904      * @name setByDateValue
3905      * @memberOf KJUR.asn1.DERAbstractTime#
3906      * @function
3907      * @param {Integer} year year of date (ex. 2013)
3908      * @param {Integer} month month of date between 1 and 12 (ex. 12)
3909      * @param {Integer} day day of month
3910      * @param {Integer} hour hours of date
3911      * @param {Integer} min minutes of date
3912      * @param {Integer} sec seconds of date
3913      */
3914     this.setByDateValue = function(year, month, day, hour, min, sec) {
3915         var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
3916         this.setByDate(dateObject);
3917     };
3918
3919     this.getFreshValueHex = function() {
3920         return this.hV;
3921     };
3922 };
3923 YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
3924 // == END   DERAbstractTime ==================================================
3925
3926 // == BEGIN DERAbstractStructured ============================================
3927 /**
3928  * base class for ASN.1 DER structured class
3929  * @name KJUR.asn1.DERAbstractStructured
3930  * @class base class for ASN.1 DER structured class
3931  * @property {Array} asn1Array internal array of ASN1Object
3932  * @extends KJUR.asn1.ASN1Object
3933  * @description
3934  * @see KJUR.asn1.ASN1Object - superclass
3935  */
3936 KJUR.asn1.DERAbstractStructured = function(params) {
3937     KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3938
3939     /**
3940      * set value by array of ASN1Object
3941      * @name setByASN1ObjectArray
3942      * @memberOf KJUR.asn1.DERAbstractStructured#
3943      * @function
3944      * @param {array} asn1ObjectArray array of ASN1Object to set
3945      */
3946     this.setByASN1ObjectArray = function(asn1ObjectArray) {
3947         this.hTLV = null;
3948         this.isModified = true;
3949         this.asn1Array = asn1ObjectArray;
3950     };
3951
3952     /**
3953      * append an ASN1Object to internal array
3954      * @name appendASN1Object
3955      * @memberOf KJUR.asn1.DERAbstractStructured#
3956      * @function
3957      * @param {ASN1Object} asn1Object to add
3958      */
3959     this.appendASN1Object = function(asn1Object) {
3960         this.hTLV = null;
3961         this.isModified = true;
3962         this.asn1Array.push(asn1Object);
3963     };
3964
3965     this.asn1Array = new Array();
3966     if (typeof params != "undefined") {
3967         if (typeof params['array'] != "undefined") {
3968             this.asn1Array = params['array'];
3969         }
3970     }
3971 };
3972 YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
3973
3974
3975 // ********************************************************************
3976 //  ASN.1 Object Classes
3977 // ********************************************************************
3978
3979 // ********************************************************************
3980 /**
3981  * class for ASN.1 DER Boolean
3982  * @name KJUR.asn1.DERBoolean
3983  * @class class for ASN.1 DER Boolean
3984  * @extends KJUR.asn1.ASN1Object
3985  * @description
3986  * @see KJUR.asn1.ASN1Object - superclass
3987  */
3988 KJUR.asn1.DERBoolean = function() {
3989     KJUR.asn1.DERBoolean.superclass.constructor.call(this);
3990     this.hT = "01";
3991     this.hTLV = "0101ff";
3992 };
3993 YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
3994
3995 // ********************************************************************
3996 /**
3997  * class for ASN.1 DER Integer
3998  * @name KJUR.asn1.DERInteger
3999  * @class class for ASN.1 DER Integer
4000  * @extends KJUR.asn1.ASN1Object
4001  * @description
4002  * <br/>
4003  * As for argument 'params' for constructor, you can specify one of
4004  * following properties:
4005  * <ul>
4006  * <li>int - specify initial ASN.1 value(V) by integer value</li>
4007  * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
4008  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4009  * </ul>
4010  * NOTE: 'params' can be omitted.
4011  */
4012 KJUR.asn1.DERInteger = function(params) {
4013     KJUR.asn1.DERInteger.superclass.constructor.call(this);
4014     this.hT = "02";
4015
4016     /**
4017      * set value by Tom Wu's BigInteger object
4018      * @name setByBigInteger
4019      * @memberOf KJUR.asn1.DERInteger#
4020      * @function
4021      * @param {BigInteger} bigIntegerValue to set
4022      */
4023     this.setByBigInteger = function(bigIntegerValue) {
4024         this.hTLV = null;
4025         this.isModified = true;
4026         this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4027     };
4028
4029     /**
4030      * set value by integer value
4031      * @name setByInteger
4032      * @memberOf KJUR.asn1.DERInteger
4033      * @function
4034      * @param {Integer} integer value to set
4035      */
4036     this.setByInteger = function(intValue) {
4037         var bi = new BigInteger(String(intValue), 10);
4038         this.setByBigInteger(bi);
4039     };
4040
4041     /**
4042      * set value by integer value
4043      * @name setValueHex
4044      * @memberOf KJUR.asn1.DERInteger#
4045      * @function
4046      * @param {String} hexadecimal string of integer value
4047      * @description
4048      * <br/>
4049      * NOTE: Value shall be represented by minimum octet length of
4050      * two's complement representation.
4051      * @example
4052      * new KJUR.asn1.DERInteger(123);
4053      * new KJUR.asn1.DERInteger({'int': 123});
4054      * new KJUR.asn1.DERInteger({'hex': '1fad'});
4055      */
4056     this.setValueHex = function(newHexString) {
4057         this.hV = newHexString;
4058     };
4059
4060     this.getFreshValueHex = function() {
4061         return this.hV;
4062     };
4063
4064     if (typeof params != "undefined") {
4065         if (typeof params['bigint'] != "undefined") {
4066             this.setByBigInteger(params['bigint']);
4067         } else if (typeof params['int'] != "undefined") {
4068             this.setByInteger(params['int']);
4069         } else if (typeof params == "number") {
4070             this.setByInteger(params);
4071         } else if (typeof params['hex'] != "undefined") {
4072             this.setValueHex(params['hex']);
4073         }
4074     }
4075 };
4076 YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
4077
4078 // ********************************************************************
4079 /**
4080  * class for ASN.1 DER encoded BitString primitive
4081  * @name KJUR.asn1.DERBitString
4082  * @class class for ASN.1 DER encoded BitString primitive
4083  * @extends KJUR.asn1.ASN1Object
4084  * @description
4085  * <br/>
4086  * As for argument 'params' for constructor, you can specify one of
4087  * following properties:
4088  * <ul>
4089  * <li>bin - specify binary string (ex. '10111')</li>
4090  * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
4091  * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
4092  * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
4093  * argument for "BitString encapsulates" structure.</li>
4094  * </ul>
4095  * NOTE1: 'params' can be omitted.<br/>
4096  * NOTE2: 'obj' parameter have been supported since
4097  * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
4098  * @example
4099  * // default constructor
4100  * o = new KJUR.asn1.DERBitString();
4101  * // initialize with binary string
4102  * o = new KJUR.asn1.DERBitString({bin: "1011"});
4103  * // initialize with boolean array
4104  * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
4105  * // initialize with hexadecimal string (04 is unused bits)
4106  * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
4107  * // initialize with ASN1Util.newObject argument for encapsulated
4108  * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4109  * // above generates a ASN.1 data like this:
4110  * // BIT STRING, encapsulates {
4111  * //   SEQUENCE {
4112  * //     INTEGER 3
4113  * //     PrintableString 'aaa'
4114  * //     }
4115  * //   }
4116  */
4117 KJUR.asn1.DERBitString = function(params) {
4118     if (params !== undefined && typeof params.obj !== "undefined") {
4119         var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4120         params.hex = "00" + o.getEncodedHex();
4121     }
4122     KJUR.asn1.DERBitString.superclass.constructor.call(this);
4123     this.hT = "03";
4124
4125     /**
4126      * set ASN.1 value(V) by a hexadecimal string including unused bits
4127      * @name setHexValueIncludingUnusedBits
4128      * @memberOf KJUR.asn1.DERBitString#
4129      * @function
4130      * @param {String} newHexStringIncludingUnusedBits
4131      */
4132     this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
4133         this.hTLV = null;
4134         this.isModified = true;
4135         this.hV = newHexStringIncludingUnusedBits;
4136     };
4137
4138     /**
4139      * set ASN.1 value(V) by unused bit and hexadecimal string of value
4140      * @name setUnusedBitsAndHexValue
4141      * @memberOf KJUR.asn1.DERBitString#
4142      * @function
4143      * @param {Integer} unusedBits
4144      * @param {String} hValue
4145      */
4146     this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
4147         if (unusedBits < 0 || 7 < unusedBits) {
4148             throw "unused bits shall be from 0 to 7: u = " + unusedBits;
4149         }
4150         var hUnusedBits = "0" + unusedBits;
4151         this.hTLV = null;
4152         this.isModified = true;
4153         this.hV = hUnusedBits + hValue;
4154     };
4155
4156     /**
4157      * set ASN.1 DER BitString by binary string<br/>
4158      * @name setByBinaryString
4159      * @memberOf KJUR.asn1.DERBitString#
4160      * @function
4161      * @param {String} binaryString binary value string (i.e. '10111')
4162      * @description
4163      * Its unused bits will be calculated automatically by length of
4164      * 'binaryValue'. <br/>
4165      * NOTE: Trailing zeros '0' will be ignored.
4166      * @example
4167      * o = new KJUR.asn1.DERBitString();
4168      * o.setByBooleanArray("01011");
4169      */
4170     this.setByBinaryString = function(binaryString) {
4171         binaryString = binaryString.replace(/0+$/, '');
4172         var unusedBits = 8 - binaryString.length % 8;
4173         if (unusedBits == 8) unusedBits = 0;
4174         for (var i = 0; i <= unusedBits; i++) {
4175             binaryString += '0';
4176         }
4177         var h = '';
4178         for (var i = 0; i < binaryString.length - 1; i += 8) {
4179             var b = binaryString.substr(i, 8);
4180             var x = parseInt(b, 2).toString(16);
4181             if (x.length == 1) x = '0' + x;
4182             h += x;
4183         }
4184         this.hTLV = null;
4185         this.isModified = true;
4186         this.hV = '0' + unusedBits + h;
4187     };
4188
4189     /**
4190      * set ASN.1 TLV value(V) by an array of boolean<br/>
4191      * @name setByBooleanArray
4192      * @memberOf KJUR.asn1.DERBitString#
4193      * @function
4194      * @param {array} booleanArray array of boolean (ex. [true, false, true])
4195      * @description
4196      * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
4197      * @example
4198      * o = new KJUR.asn1.DERBitString();
4199      * o.setByBooleanArray([false, true, false, true, true]);
4200      */
4201     this.setByBooleanArray = function(booleanArray) {
4202         var s = '';
4203         for (var i = 0; i < booleanArray.length; i++) {
4204             if (booleanArray[i] == true) {
4205                 s += '1';
4206             } else {
4207                 s += '0';
4208             }
4209         }
4210         this.setByBinaryString(s);
4211     };
4212
4213     /**
4214      * generate an array of falses with specified length<br/>
4215      * @name newFalseArray
4216      * @memberOf KJUR.asn1.DERBitString
4217      * @function
4218      * @param {Integer} nLength length of array to generate
4219      * @return {array} array of boolean falses
4220      * @description
4221      * This static method may be useful to initialize boolean array.
4222      * @example
4223      * o = new KJUR.asn1.DERBitString();
4224      * o.newFalseArray(3) &rarr; [false, false, false]
4225      */
4226     this.newFalseArray = function(nLength) {
4227         var a = new Array(nLength);
4228         for (var i = 0; i < nLength; i++) {
4229             a[i] = false;
4230         }
4231         return a;
4232     };
4233
4234     this.getFreshValueHex = function() {
4235         return this.hV;
4236     };
4237
4238     if (typeof params != "undefined") {
4239         if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
4240             this.setHexValueIncludingUnusedBits(params);
4241         } else if (typeof params['hex'] != "undefined") {
4242             this.setHexValueIncludingUnusedBits(params['hex']);
4243         } else if (typeof params['bin'] != "undefined") {
4244             this.setByBinaryString(params['bin']);
4245         } else if (typeof params['array'] != "undefined") {
4246             this.setByBooleanArray(params['array']);
4247         }
4248     }
4249 };
4250 YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
4251
4252 // ********************************************************************
4253 /**
4254  * class for ASN.1 DER OctetString<br/>
4255  * @name KJUR.asn1.DEROctetString
4256  * @class class for ASN.1 DER OctetString
4257  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4258  * @extends KJUR.asn1.DERAbstractString
4259  * @description
4260  * This class provides ASN.1 OctetString simple type.<br/>
4261  * Supported "params" attributes are:
4262  * <ul>
4263  * <li>str - to set a string as a value</li>
4264  * <li>hex - to set a hexadecimal string as a value</li>
4265  * <li>obj - to set a encapsulated ASN.1 value by JSON object
4266  * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
4267  * </ul>
4268  * NOTE: A parameter 'obj' have been supported
4269  * for "OCTET STRING, encapsulates" structure.
4270  * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
4271  * @see KJUR.asn1.DERAbstractString - superclass
4272  * @example
4273  * // default constructor
4274  * o = new KJUR.asn1.DEROctetString();
4275  * // initialize with string
4276  * o = new KJUR.asn1.DEROctetString({str: "aaa"});
4277  * // initialize with hexadecimal string
4278  * o = new KJUR.asn1.DEROctetString({hex: "616161"});
4279  * // initialize with ASN1Util.newObject argument
4280  * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4281  * // above generates a ASN.1 data like this:
4282  * // OCTET STRING, encapsulates {
4283  * //   SEQUENCE {
4284  * //     INTEGER 3
4285  * //     PrintableString 'aaa'
4286  * //     }
4287  * //   }
4288  */
4289 KJUR.asn1.DEROctetString = function(params) {
4290     if (params !== undefined && typeof params.obj !== "undefined") {
4291         var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4292         params.hex = o.getEncodedHex();
4293     }
4294     KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
4295     this.hT = "04";
4296 };
4297 YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
4298
4299 // ********************************************************************
4300 /**
4301  * class for ASN.1 DER Null
4302  * @name KJUR.asn1.DERNull
4303  * @class class for ASN.1 DER Null
4304  * @extends KJUR.asn1.ASN1Object
4305  * @description
4306  * @see KJUR.asn1.ASN1Object - superclass
4307  */
4308 KJUR.asn1.DERNull = function() {
4309     KJUR.asn1.DERNull.superclass.constructor.call(this);
4310     this.hT = "05";
4311     this.hTLV = "0500";
4312 };
4313 YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
4314
4315 // ********************************************************************
4316 /**
4317  * class for ASN.1 DER ObjectIdentifier
4318  * @name KJUR.asn1.DERObjectIdentifier
4319  * @class class for ASN.1 DER ObjectIdentifier
4320  * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
4321  * @extends KJUR.asn1.ASN1Object
4322  * @description
4323  * <br/>
4324  * As for argument 'params' for constructor, you can specify one of
4325  * following properties:
4326  * <ul>
4327  * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
4328  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4329  * </ul>
4330  * NOTE: 'params' can be omitted.
4331  */
4332 KJUR.asn1.DERObjectIdentifier = function(params) {
4333     var itox = function(i) {
4334         var h = i.toString(16);
4335         if (h.length == 1) h = '0' + h;
4336         return h;
4337     };
4338     var roidtox = function(roid) {
4339         var h = '';
4340         var bi = new BigInteger(roid, 10);
4341         var b = bi.toString(2);
4342         var padLen = 7 - b.length % 7;
4343         if (padLen == 7) padLen = 0;
4344         var bPad = '';
4345         for (var i = 0; i < padLen; i++) bPad += '0';
4346         b = bPad + b;
4347         for (var i = 0; i < b.length - 1; i += 7) {
4348             var b8 = b.substr(i, 7);
4349             if (i != b.length - 7) b8 = '1' + b8;
4350             h += itox(parseInt(b8, 2));
4351         }
4352         return h;
4353     };
4354
4355     KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
4356     this.hT = "06";
4357
4358     /**
4359      * set value by a hexadecimal string
4360      * @name setValueHex
4361      * @memberOf KJUR.asn1.DERObjectIdentifier#
4362      * @function
4363      * @param {String} newHexString hexadecimal value of OID bytes
4364      */
4365     this.setValueHex = function(newHexString) {
4366         this.hTLV = null;
4367         this.isModified = true;
4368         this.s = null;
4369         this.hV = newHexString;
4370     };
4371
4372     /**
4373      * set value by a OID string<br/>
4374      * @name setValueOidString
4375      * @memberOf KJUR.asn1.DERObjectIdentifier#
4376      * @function
4377      * @param {String} oidString OID string (ex. 2.5.4.13)
4378      * @example
4379      * o = new KJUR.asn1.DERObjectIdentifier();
4380      * o.setValueOidString("2.5.4.13");
4381      */
4382     this.setValueOidString = function(oidString) {
4383         if (! oidString.match(/^[0-9.]+$/)) {
4384             throw "malformed oid string: " + oidString;
4385         }
4386         var h = '';
4387         var a = oidString.split('.');
4388         var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
4389         h += itox(i0);
4390         a.splice(0, 2);
4391         for (var i = 0; i < a.length; i++) {
4392             h += roidtox(a[i]);
4393         }
4394         this.hTLV = null;
4395         this.isModified = true;
4396         this.s = null;
4397         this.hV = h;
4398     };
4399
4400     /**
4401      * set value by a OID name
4402      * @name setValueName
4403      * @memberOf KJUR.asn1.DERObjectIdentifier#
4404      * @function
4405      * @param {String} oidName OID name (ex. 'serverAuth')
4406      * @since 1.0.1
4407      * @description
4408      * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
4409      * Otherwise raise error.
4410      * @example
4411      * o = new KJUR.asn1.DERObjectIdentifier();
4412      * o.setValueName("serverAuth");
4413      */
4414     this.setValueName = function(oidName) {
4415         var oid = KJUR.asn1.x509.OID.name2oid(oidName);
4416         if (oid !== '') {
4417             this.setValueOidString(oid);
4418         } else {
4419             throw "DERObjectIdentifier oidName undefined: " + oidName;
4420         }
4421     };
4422
4423     this.getFreshValueHex = function() {
4424         return this.hV;
4425     };
4426
4427     if (params !== undefined) {
4428         if (typeof params === "string") {
4429             if (params.match(/^[0-2].[0-9.]+$/)) {
4430                 this.setValueOidString(params);
4431             } else {
4432                 this.setValueName(params);
4433             }
4434         } else if (params.oid !== undefined) {
4435             this.setValueOidString(params.oid);
4436         } else if (params.hex !== undefined) {
4437             this.setValueHex(params.hex);
4438         } else if (params.name !== undefined) {
4439             this.setValueName(params.name);
4440         }
4441     }
4442 };
4443 YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
4444
4445 // ********************************************************************
4446 /**
4447  * class for ASN.1 DER Enumerated
4448  * @name KJUR.asn1.DEREnumerated
4449  * @class class for ASN.1 DER Enumerated
4450  * @extends KJUR.asn1.ASN1Object
4451  * @description
4452  * <br/>
4453  * As for argument 'params' for constructor, you can specify one of
4454  * following properties:
4455  * <ul>
4456  * <li>int - specify initial ASN.1 value(V) by integer value</li>
4457  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4458  * </ul>
4459  * NOTE: 'params' can be omitted.
4460  * @example
4461  * new KJUR.asn1.DEREnumerated(123);
4462  * new KJUR.asn1.DEREnumerated({int: 123});
4463  * new KJUR.asn1.DEREnumerated({hex: '1fad'});
4464  */
4465 KJUR.asn1.DEREnumerated = function(params) {
4466     KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
4467     this.hT = "0a";
4468
4469     /**
4470      * set value by Tom Wu's BigInteger object
4471      * @name setByBigInteger
4472      * @memberOf KJUR.asn1.DEREnumerated#
4473      * @function
4474      * @param {BigInteger} bigIntegerValue to set
4475      */
4476     this.setByBigInteger = function(bigIntegerValue) {
4477         this.hTLV = null;
4478         this.isModified = true;
4479         this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4480     };
4481
4482     /**
4483      * set value by integer value
4484      * @name setByInteger
4485      * @memberOf KJUR.asn1.DEREnumerated#
4486      * @function
4487      * @param {Integer} integer value to set
4488      */
4489     this.setByInteger = function(intValue) {
4490         var bi = new BigInteger(String(intValue), 10);
4491         this.setByBigInteger(bi);
4492     };
4493
4494     /**
4495      * set value by integer value
4496      * @name setValueHex
4497      * @memberOf KJUR.asn1.DEREnumerated#
4498      * @function
4499      * @param {String} hexadecimal string of integer value
4500      * @description
4501      * <br/>
4502      * NOTE: Value shall be represented by minimum octet length of
4503      * two's complement representation.
4504      */
4505     this.setValueHex = function(newHexString) {
4506         this.hV = newHexString;
4507     };
4508
4509     this.getFreshValueHex = function() {
4510         return this.hV;
4511     };
4512
4513     if (typeof params != "undefined") {
4514         if (typeof params['int'] != "undefined") {
4515             this.setByInteger(params['int']);
4516         } else if (typeof params == "number") {
4517             this.setByInteger(params);
4518         } else if (typeof params['hex'] != "undefined") {
4519             this.setValueHex(params['hex']);
4520         }
4521     }
4522 };
4523 YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
4524
4525 // ********************************************************************
4526 /**
4527  * class for ASN.1 DER UTF8String
4528  * @name KJUR.asn1.DERUTF8String
4529  * @class class for ASN.1 DER UTF8String
4530  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4531  * @extends KJUR.asn1.DERAbstractString
4532  * @description
4533  * @see KJUR.asn1.DERAbstractString - superclass
4534  */
4535 KJUR.asn1.DERUTF8String = function(params) {
4536     KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
4537     this.hT = "0c";
4538 };
4539 YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
4540
4541 // ********************************************************************
4542 /**
4543  * class for ASN.1 DER NumericString
4544  * @name KJUR.asn1.DERNumericString
4545  * @class class for ASN.1 DER NumericString
4546  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4547  * @extends KJUR.asn1.DERAbstractString
4548  * @description
4549  * @see KJUR.asn1.DERAbstractString - superclass
4550  */
4551 KJUR.asn1.DERNumericString = function(params) {
4552     KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
4553     this.hT = "12";
4554 };
4555 YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
4556
4557 // ********************************************************************
4558 /**
4559  * class for ASN.1 DER PrintableString
4560  * @name KJUR.asn1.DERPrintableString
4561  * @class class for ASN.1 DER PrintableString
4562  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4563  * @extends KJUR.asn1.DERAbstractString
4564  * @description
4565  * @see KJUR.asn1.DERAbstractString - superclass
4566  */
4567 KJUR.asn1.DERPrintableString = function(params) {
4568     KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
4569     this.hT = "13";
4570 };
4571 YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
4572
4573 // ********************************************************************
4574 /**
4575  * class for ASN.1 DER TeletexString
4576  * @name KJUR.asn1.DERTeletexString
4577  * @class class for ASN.1 DER TeletexString
4578  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4579  * @extends KJUR.asn1.DERAbstractString
4580  * @description
4581  * @see KJUR.asn1.DERAbstractString - superclass
4582  */
4583 KJUR.asn1.DERTeletexString = function(params) {
4584     KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
4585     this.hT = "14";
4586 };
4587 YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
4588
4589 // ********************************************************************
4590 /**
4591  * class for ASN.1 DER IA5String
4592  * @name KJUR.asn1.DERIA5String
4593  * @class class for ASN.1 DER IA5String
4594  * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4595  * @extends KJUR.asn1.DERAbstractString
4596  * @description
4597  * @see KJUR.asn1.DERAbstractString - superclass
4598  */
4599 KJUR.asn1.DERIA5String = function(params) {
4600     KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
4601     this.hT = "16";
4602 };
4603 YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
4604
4605 // ********************************************************************
4606 /**
4607  * class for ASN.1 DER UTCTime
4608  * @name KJUR.asn1.DERUTCTime
4609  * @class class for ASN.1 DER UTCTime
4610  * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
4611  * @extends KJUR.asn1.DERAbstractTime
4612  * @description
4613  * <br/>
4614  * As for argument 'params' for constructor, you can specify one of
4615  * following properties:
4616  * <ul>
4617  * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
4618  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4619  * <li>date - specify Date object.</li>
4620  * </ul>
4621  * NOTE: 'params' can be omitted.
4622  * <h4>EXAMPLES</h4>
4623  * @example
4624  * d1 = new KJUR.asn1.DERUTCTime();
4625  * d1.setString('130430125959Z');
4626  *
4627  * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
4628  * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
4629  * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
4630  */
4631 KJUR.asn1.DERUTCTime = function(params) {
4632     KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
4633     this.hT = "17";
4634
4635     /**
4636      * set value by a Date object<br/>
4637      * @name setByDate
4638      * @memberOf KJUR.asn1.DERUTCTime#
4639      * @function
4640      * @param {Date} dateObject Date object to set ASN.1 value(V)
4641      * @example
4642      * o = new KJUR.asn1.DERUTCTime();
4643      * o.setByDate(new Date("2016/12/31"));
4644      */
4645     this.setByDate = function(dateObject) {
4646         this.hTLV = null;
4647         this.isModified = true;
4648         this.date = dateObject;
4649         this.s = this.formatDate(this.date, 'utc');
4650         this.hV = stohex(this.s);
4651     };
4652
4653     this.getFreshValueHex = function() {
4654         if (typeof this.date == "undefined" && typeof this.s == "undefined") {
4655             this.date = new Date();
4656             this.s = this.formatDate(this.date, 'utc');
4657             this.hV = stohex(this.s);
4658         }
4659         return this.hV;
4660     };
4661
4662     if (params !== undefined) {
4663         if (params.str !== undefined) {
4664             this.setString(params.str);
4665         } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
4666             this.setString(params);
4667         } else if (params.hex !== undefined) {
4668             this.setStringHex(params.hex);
4669         } else if (params.date !== undefined) {
4670             this.setByDate(params.date);
4671         }
4672     }
4673 };
4674 YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
4675
4676 // ********************************************************************
4677 /**
4678  * class for ASN.1 DER GeneralizedTime
4679  * @name KJUR.asn1.DERGeneralizedTime
4680  * @class class for ASN.1 DER GeneralizedTime
4681  * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
4682  * @property {Boolean} withMillis flag to show milliseconds or not
4683  * @extends KJUR.asn1.DERAbstractTime
4684  * @description
4685  * <br/>
4686  * As for argument 'params' for constructor, you can specify one of
4687  * following properties:
4688  * <ul>
4689  * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
4690  * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4691  * <li>date - specify Date object.</li>
4692  * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
4693  * </ul>
4694  * NOTE1: 'params' can be omitted.
4695  * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
4696  */
4697 KJUR.asn1.DERGeneralizedTime = function(params) {
4698     KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
4699     this.hT = "18";
4700     this.withMillis = false;
4701
4702     /**
4703      * set value by a Date object
4704      * @name setByDate
4705      * @memberOf KJUR.asn1.DERGeneralizedTime#
4706      * @function
4707      * @param {Date} dateObject Date object to set ASN.1 value(V)
4708      * @example
4709      * When you specify UTC time, use 'Date.UTC' method like this:<br/>
4710      * o1 = new DERUTCTime();
4711      * o1.setByDate(date);
4712      *
4713      * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
4714      */
4715     this.setByDate = function(dateObject) {
4716         this.hTLV = null;
4717         this.isModified = true;
4718         this.date = dateObject;
4719         this.s = this.formatDate(this.date, 'gen', this.withMillis);
4720         this.hV = stohex(this.s);
4721     };
4722
4723     this.getFreshValueHex = function() {
4724         if (this.date === undefined && this.s === undefined) {
4725             this.date = new Date();
4726             this.s = this.formatDate(this.date, 'gen', this.withMillis);
4727             this.hV = stohex(this.s);
4728         }
4729         return this.hV;
4730     };
4731
4732     if (params !== undefined) {
4733         if (params.str !== undefined) {
4734             this.setString(params.str);
4735         } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
4736             this.setString(params);
4737         } else if (params.hex !== undefined) {
4738             this.setStringHex(params.hex);
4739         } else if (params.date !== undefined) {
4740             this.setByDate(params.date);
4741         }
4742         if (params.millis === true) {
4743             this.withMillis = true;
4744         }
4745     }
4746 };
4747 YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
4748
4749 // ********************************************************************
4750 /**
4751  * class for ASN.1 DER Sequence
4752  * @name KJUR.asn1.DERSequence
4753  * @class class for ASN.1 DER Sequence
4754  * @extends KJUR.asn1.DERAbstractStructured
4755  * @description
4756  * <br/>
4757  * As for argument 'params' for constructor, you can specify one of
4758  * following properties:
4759  * <ul>
4760  * <li>array - specify array of ASN1Object to set elements of content</li>
4761  * </ul>
4762  * NOTE: 'params' can be omitted.
4763  */
4764 KJUR.asn1.DERSequence = function(params) {
4765     KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
4766     this.hT = "30";
4767     this.getFreshValueHex = function() {
4768         var h = '';
4769         for (var i = 0; i < this.asn1Array.length; i++) {
4770             var asn1Obj = this.asn1Array[i];
4771             h += asn1Obj.getEncodedHex();
4772         }
4773         this.hV = h;
4774         return this.hV;
4775     };
4776 };
4777 YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
4778
4779 // ********************************************************************
4780 /**
4781  * class for ASN.1 DER Set
4782  * @name KJUR.asn1.DERSet
4783  * @class class for ASN.1 DER Set
4784  * @extends KJUR.asn1.DERAbstractStructured
4785  * @description
4786  * <br/>
4787  * As for argument 'params' for constructor, you can specify one of
4788  * following properties:
4789  * <ul>
4790  * <li>array - specify array of ASN1Object to set elements of content</li>
4791  * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
4792  * </ul>
4793  * NOTE1: 'params' can be omitted.<br/>
4794  * NOTE2: sortflag is supported since 1.0.5.
4795  */
4796 KJUR.asn1.DERSet = function(params) {
4797     KJUR.asn1.DERSet.superclass.constructor.call(this, params);
4798     this.hT = "31";
4799     this.sortFlag = true; // item shall be sorted only in ASN.1 DER
4800     this.getFreshValueHex = function() {
4801         var a = new Array();
4802         for (var i = 0; i < this.asn1Array.length; i++) {
4803             var asn1Obj = this.asn1Array[i];
4804             a.push(asn1Obj.getEncodedHex());
4805         }
4806         if (this.sortFlag == true) a.sort();
4807         this.hV = a.join('');
4808         return this.hV;
4809     };
4810
4811     if (typeof params != "undefined") {
4812         if (typeof params.sortflag != "undefined" &&
4813             params.sortflag == false)
4814             this.sortFlag = false;
4815     }
4816 };
4817 YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
4818
4819 // ********************************************************************
4820 /**
4821  * class for ASN.1 DER TaggedObject
4822  * @name KJUR.asn1.DERTaggedObject
4823  * @class class for ASN.1 DER TaggedObject
4824  * @extends KJUR.asn1.ASN1Object
4825  * @description
4826  * <br/>
4827  * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
4828  * For example, if you find '[1]' tag in a ASN.1 dump,
4829  * 'tagNoHex' will be 'a1'.
4830  * <br/>
4831  * As for optional argument 'params' for constructor, you can specify *ANY* of
4832  * following properties:
4833  * <ul>
4834  * <li>explicit - specify true if this is explicit tag otherwise false
4835  *     (default is 'true').</li>
4836  * <li>tag - specify tag (default is 'a0' which means [0])</li>
4837  * <li>obj - specify ASN1Object which is tagged</li>
4838  * </ul>
4839  * @example
4840  * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
4841  * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
4842  * hex = d2.getEncodedHex();
4843  */
4844 KJUR.asn1.DERTaggedObject = function(params) {
4845     KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
4846     this.hT = "a0";
4847     this.hV = '';
4848     this.isExplicit = true;
4849     this.asn1Object = null;
4850
4851     /**
4852      * set value by an ASN1Object
4853      * @name setString
4854      * @memberOf KJUR.asn1.DERTaggedObject#
4855      * @function
4856      * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
4857      * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
4858      * @param {ASN1Object} asn1Object ASN.1 to encapsulate
4859      */
4860     this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
4861         this.hT = tagNoHex;
4862         this.isExplicit = isExplicitFlag;
4863         this.asn1Object = asn1Object;
4864         if (this.isExplicit) {
4865             this.hV = this.asn1Object.getEncodedHex();
4866             this.hTLV = null;
4867             this.isModified = true;
4868         } else {
4869             this.hV = null;
4870             this.hTLV = asn1Object.getEncodedHex();
4871             this.hTLV = this.hTLV.replace(/^../, tagNoHex);
4872             this.isModified = false;
4873         }
4874     };
4875
4876     this.getFreshValueHex = function() {
4877         return this.hV;
4878     };
4879
4880     if (typeof params != "undefined") {
4881         if (typeof params['tag'] != "undefined") {
4882             this.hT = params['tag'];
4883         }
4884         if (typeof params['explicit'] != "undefined") {
4885             this.isExplicit = params['explicit'];
4886         }
4887         if (typeof params['obj'] != "undefined") {
4888             this.asn1Object = params['obj'];
4889             this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
4890         }
4891     }
4892 };
4893 YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
4894
4895 /**
4896  * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
4897  * This object is just a decorator for parsing the key parameter
4898  * @param {string|Object} key - The key in string format, or an object containing
4899  * the parameters needed to build a RSAKey object.
4900  * @constructor
4901  */
4902 var JSEncryptRSAKey = /** @class */ (function (_super) {
4903     __extends(JSEncryptRSAKey, _super);
4904     function JSEncryptRSAKey(key) {
4905         var _this = _super.call(this) || this;
4906         // Call the super constructor.
4907         //  RSAKey.call(this);
4908         // If a key key was provided.
4909         if (key) {
4910             // If this is a string...
4911             if (typeof key === "string") {
4912                 _this.parseKey(key);
4913             }
4914             else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
4915                 JSEncryptRSAKey.hasPublicKeyProperty(key)) {
4916                 // Set the values for the key.
4917                 _this.parsePropertiesFrom(key);
4918             }
4919         }
4920         return _this;
4921     }
4922     /**
4923      * Method to parse a pem encoded string containing both a public or private key.
4924      * The method will translate the pem encoded string in a der encoded string and
4925      * will parse private key and public key parameters. This method accepts public key
4926      * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
4927      *
4928      * @todo Check how many rsa formats use the same format of pkcs #1.
4929      *
4930      * The format is defined as:
4931      * PublicKeyInfo ::= SEQUENCE {
4932      *   algorithm       AlgorithmIdentifier,
4933      *   PublicKey       BIT STRING
4934      * }
4935      * Where AlgorithmIdentifier is:
4936      * AlgorithmIdentifier ::= SEQUENCE {
4937      *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
4938      *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
4939      * }
4940      * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
4941      * RSAPublicKey ::= SEQUENCE {
4942      *   modulus           INTEGER,  -- n
4943      *   publicExponent    INTEGER   -- e
4944      * }
4945      * it's possible to examine the structure of the keys obtained from openssl using
4946      * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
4947      * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
4948      * @private
4949      */
4950     JSEncryptRSAKey.prototype.parseKey = function (pem) {
4951         try {
4952             var modulus = 0;
4953             var public_exponent = 0;
4954             var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
4955             var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
4956             var asn1 = ASN1.decode(der);
4957             // Fixes a bug with OpenSSL 1.0+ private keys
4958             if (asn1.sub.length === 3) {
4959                 asn1 = asn1.sub[2].sub[0];
4960             }
4961             if (asn1.sub.length === 9) {
4962                 // Parse the private key.
4963                 modulus = asn1.sub[1].getHexStringValue(); // bigint
4964                 this.n = parseBigInt(modulus, 16);
4965                 public_exponent = asn1.sub[2].getHexStringValue(); // int
4966                 this.e = parseInt(public_exponent, 16);
4967                 var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
4968                 this.d = parseBigInt(private_exponent, 16);
4969                 var prime1 = asn1.sub[4].getHexStringValue(); // bigint
4970                 this.p = parseBigInt(prime1, 16);
4971                 var prime2 = asn1.sub[5].getHexStringValue(); // bigint
4972                 this.q = parseBigInt(prime2, 16);
4973                 var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
4974                 this.dmp1 = parseBigInt(exponent1, 16);
4975                 var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
4976                 this.dmq1 = parseBigInt(exponent2, 16);
4977                 var coefficient = asn1.sub[8].getHexStringValue(); // bigint
4978                 this.coeff = parseBigInt(coefficient, 16);
4979             }
4980             else if (asn1.sub.length === 2) {
4981                 // Parse the public key.
4982                 var bit_string = asn1.sub[1];
4983                 var sequence = bit_string.sub[0];
4984                 modulus = sequence.sub[0].getHexStringValue();
4985                 this.n = parseBigInt(modulus, 16);
4986                 public_exponent = sequence.sub[1].getHexStringValue();
4987                 this.e = parseInt(public_exponent, 16);
4988             }
4989             else {
4990                 return false;
4991             }
4992             return true;
4993         }
4994         catch (ex) {
4995             return false;
4996         }
4997     };
4998     /**
4999      * Translate rsa parameters in a hex encoded string representing the rsa key.
5000      *
5001      * The translation follow the ASN.1 notation :
5002      * RSAPrivateKey ::= SEQUENCE {
5003      *   version           Version,
5004      *   modulus           INTEGER,  -- n
5005      *   publicExponent    INTEGER,  -- e
5006      *   privateExponent   INTEGER,  -- d
5007      *   prime1            INTEGER,  -- p
5008      *   prime2            INTEGER,  -- q
5009      *   exponent1         INTEGER,  -- d mod (p1)
5010      *   exponent2         INTEGER,  -- d mod (q-1)
5011      *   coefficient       INTEGER,  -- (inverse of q) mod p
5012      * }
5013      * @returns {string}  DER Encoded String representing the rsa private key
5014      * @private
5015      */
5016     JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
5017         var options = {
5018             array: [
5019                 new KJUR.asn1.DERInteger({ int: 0 }),
5020                 new KJUR.asn1.DERInteger({ bigint: this.n }),
5021                 new KJUR.asn1.DERInteger({ int: this.e }),
5022                 new KJUR.asn1.DERInteger({ bigint: this.d }),
5023                 new KJUR.asn1.DERInteger({ bigint: this.p }),
5024                 new KJUR.asn1.DERInteger({ bigint: this.q }),
5025                 new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
5026                 new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
5027                 new KJUR.asn1.DERInteger({ bigint: this.coeff })
5028             ]
5029         };
5030         var seq = new KJUR.asn1.DERSequence(options);
5031         return seq.getEncodedHex();
5032     };
5033     /**
5034      * base64 (pem) encoded version of the DER encoded representation
5035      * @returns {string} pem encoded representation without header and footer
5036      * @public
5037      */
5038     JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
5039         return hex2b64(this.getPrivateBaseKey());
5040     };
5041     /**
5042      * Translate rsa parameters in a hex encoded string representing the rsa public key.
5043      * The representation follow the ASN.1 notation :
5044      * PublicKeyInfo ::= SEQUENCE {
5045      *   algorithm       AlgorithmIdentifier,
5046      *   PublicKey       BIT STRING
5047      * }
5048      * Where AlgorithmIdentifier is:
5049      * AlgorithmIdentifier ::= SEQUENCE {
5050      *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
5051      *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
5052      * }
5053      * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
5054      * RSAPublicKey ::= SEQUENCE {
5055      *   modulus           INTEGER,  -- n
5056      *   publicExponent    INTEGER   -- e
5057      * }
5058      * @returns {string} DER Encoded String representing the rsa public key
5059      * @private
5060      */
5061     JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
5062         var first_sequence = new KJUR.asn1.DERSequence({
5063             array: [
5064                 new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
5065                 new KJUR.asn1.DERNull()
5066             ]
5067         });
5068         var second_sequence = new KJUR.asn1.DERSequence({
5069             array: [
5070                 new KJUR.asn1.DERInteger({ bigint: this.n }),
5071                 new KJUR.asn1.DERInteger({ int: this.e })
5072             ]
5073         });
5074         var bit_string = new KJUR.asn1.DERBitString({
5075             hex: "00" + second_sequence.getEncodedHex()
5076         });
5077         var seq = new KJUR.asn1.DERSequence({
5078             array: [
5079                 first_sequence,
5080                 bit_string
5081             ]
5082         });
5083         return seq.getEncodedHex();
5084     };
5085     /**
5086      * base64 (pem) encoded version of the DER encoded representation
5087      * @returns {string} pem encoded representation without header and footer
5088      * @public
5089      */
5090     JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
5091         return hex2b64(this.getPublicBaseKey());
5092     };
5093     /**
5094      * wrap the string in block of width chars. The default value for rsa keys is 64
5095      * characters.
5096      * @param {string} str the pem encoded string without header and footer
5097      * @param {Number} [width=64] - the length the string has to be wrapped at
5098      * @returns {string}
5099      * @private
5100      */
5101     JSEncryptRSAKey.wordwrap = function (str, width) {
5102         width = width || 64;
5103         if (!str) {
5104             return str;
5105         }
5106         var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
5107         return str.match(RegExp(regex, "g")).join("\n");
5108     };
5109     /**
5110      * Retrieve the pem encoded private key
5111      * @returns {string} the pem encoded private key with header/footer
5112      * @public
5113      */
5114     JSEncryptRSAKey.prototype.getPrivateKey = function () {
5115         var key = "-----BEGIN RSA PRIVATE KEY-----\n";
5116         key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
5117         key += "-----END RSA PRIVATE KEY-----";
5118         return key;
5119     };
5120     /**
5121      * Retrieve the pem encoded public key
5122      * @returns {string} the pem encoded public key with header/footer
5123      * @public
5124      */
5125     JSEncryptRSAKey.prototype.getPublicKey = function () {
5126         var key = "-----BEGIN PUBLIC KEY-----\n";
5127         key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
5128         key += "-----END PUBLIC KEY-----";
5129         return key;
5130     };
5131     /**
5132      * Check if the object contains the necessary parameters to populate the rsa modulus
5133      * and public exponent parameters.
5134      * @param {Object} [obj={}] - An object that may contain the two public key
5135      * parameters
5136      * @returns {boolean} true if the object contains both the modulus and the public exponent
5137      * properties (n and e)
5138      * @todo check for types of n and e. N should be a parseable bigInt object, E should
5139      * be a parseable integer number
5140      * @private
5141      */
5142     JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
5143         obj = obj || {};
5144         return (obj.hasOwnProperty("n") &&
5145             obj.hasOwnProperty("e"));
5146     };
5147     /**
5148      * Check if the object contains ALL the parameters of an RSA key.
5149      * @param {Object} [obj={}] - An object that may contain nine rsa key
5150      * parameters
5151      * @returns {boolean} true if the object contains all the parameters needed
5152      * @todo check for types of the parameters all the parameters but the public exponent
5153      * should be parseable bigint objects, the public exponent should be a parseable integer number
5154      * @private
5155      */
5156     JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
5157         obj = obj || {};
5158         return (obj.hasOwnProperty("n") &&
5159             obj.hasOwnProperty("e") &&
5160             obj.hasOwnProperty("d") &&
5161             obj.hasOwnProperty("p") &&
5162             obj.hasOwnProperty("q") &&
5163             obj.hasOwnProperty("dmp1") &&
5164             obj.hasOwnProperty("dmq1") &&
5165             obj.hasOwnProperty("coeff"));
5166     };
5167     /**
5168      * Parse the properties of obj in the current rsa object. Obj should AT LEAST
5169      * include the modulus and public exponent (n, e) parameters.
5170      * @param {Object} obj - the object containing rsa parameters
5171      * @private
5172      */
5173     JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
5174         this.n = obj.n;
5175         this.e = obj.e;
5176         if (obj.hasOwnProperty("d")) {
5177             this.d = obj.d;
5178             this.p = obj.p;
5179             this.q = obj.q;
5180             this.dmp1 = obj.dmp1;
5181             this.dmq1 = obj.dmq1;
5182             this.coeff = obj.coeff;
5183         }
5184     };
5185     return JSEncryptRSAKey;
5186 }(RSAKey));
5187
5188 /**
5189  *
5190  * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
5191  * possible parameters are:
5192  * - default_key_size        {number}  default: 1024 the key size in bit
5193  * - default_public_exponent {string}  default: '010001' the hexadecimal representation of the public exponent
5194  * - log                     {boolean} default: false whether log warn/error or not
5195  * @constructor
5196  */
5197 var JSEncrypt = /** @class */ (function () {
5198     function JSEncrypt(options) {
5199         options = options || {};
5200         this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
5201         this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
5202         this.log = options.log || false;
5203         // The private and public key.
5204         this.key = null;
5205     }
5206     /**
5207      * Method to set the rsa key parameter (one method is enough to set both the public
5208      * and the private key, since the private key contains the public key paramenters)
5209      * Log a warning if logs are enabled
5210      * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
5211      * @public
5212      */
5213     JSEncrypt.prototype.setKey = function (key) {
5214         if (this.log && this.key) {
5215             console.warn("A key was already set, overriding existing.");
5216         }
5217         this.key = new JSEncryptRSAKey(key);
5218     };
5219     /**
5220      * Proxy method for setKey, for api compatibility
5221      * @see setKey
5222      * @public
5223      */
5224     JSEncrypt.prototype.setPrivateKey = function (privkey) {
5225         // Create the key.
5226         this.setKey(privkey);
5227     };
5228     /**
5229      * Proxy method for setKey, for api compatibility
5230      * @see setKey
5231      * @public
5232      */
5233     JSEncrypt.prototype.setPublicKey = function (pubkey) {
5234         // Sets the public key.
5235         this.setKey(pubkey);
5236     };
5237     /**
5238      * Proxy method for RSAKey object's decrypt, decrypt the string using the private
5239      * components of the rsa key object. Note that if the object was not set will be created
5240      * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5241      * @param {string} str base64 encoded crypted string to decrypt
5242      * @return {string} the decrypted string
5243      * @public
5244      */
5245     JSEncrypt.prototype.decrypt = function (str) {
5246         // Return the decrypted string.
5247         try {
5248             return this.getKey().decrypt(b64tohex(str));
5249         }
5250         catch (ex) {
5251             return false;
5252         }
5253     };
5254     /**
5255      * Proxy method for RSAKey object's encrypt, encrypt the string using the public
5256      * components of the rsa key object. Note that if the object was not set will be created
5257      * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5258      * @param {string} str the string to encrypt
5259      * @return {string} the encrypted string encoded in base64
5260      * @public
5261      */
5262     JSEncrypt.prototype.encrypt = function (str) {
5263         // Return the encrypted string.
5264         try {
5265             return hex2b64(this.getKey().encrypt(str));
5266         }
5267         catch (ex) {
5268             return false;
5269         }
5270     };
5271     /**
5272      * Proxy method for RSAKey object's sign.
5273      * @param {string} str the string to sign
5274      * @param {function} digestMethod hash method
5275      * @param {string} digestName the name of the hash algorithm
5276      * @return {string} the signature encoded in base64
5277      * @public
5278      */
5279     JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
5280         // return the RSA signature of 'str' in 'hex' format.
5281         try {
5282             return hex2b64(this.getKey().sign(str, digestMethod, digestName));
5283         }
5284         catch (ex) {
5285             return false;
5286         }
5287     };
5288     /**
5289      * Proxy method for RSAKey object's verify.
5290      * @param {string} str the string to verify
5291      * @param {string} signature the signature encoded in base64 to compare the string to
5292      * @param {function} digestMethod hash method
5293      * @return {boolean} whether the data and signature match
5294      * @public
5295      */
5296     JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
5297         // Return the decrypted 'digest' of the signature.
5298         try {
5299             return this.getKey().verify(str, b64tohex(signature), digestMethod);
5300         }
5301         catch (ex) {
5302             return false;
5303         }
5304     };
5305     /**
5306      * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
5307      * will be created and returned
5308      * @param {callback} [cb] the callback to be called if we want the key to be generated
5309      * in an async fashion
5310      * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
5311      * @public
5312      */
5313     JSEncrypt.prototype.getKey = function (cb) {
5314         // Only create new if it does not exist.
5315         if (!this.key) {
5316             // Get a new private key.
5317             this.key = new JSEncryptRSAKey();
5318             if (cb && {}.toString.call(cb) === "[object Function]") {
5319                 this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
5320                 return;
5321             }
5322             // Generate the key.
5323             this.key.generate(this.default_key_size, this.default_public_exponent);
5324         }
5325         return this.key;
5326     };
5327     /**
5328      * Returns the pem encoded representation of the private key
5329      * If the key doesn't exists a new key will be created
5330      * @returns {string} pem encoded representation of the private key WITH header and footer
5331      * @public
5332      */
5333     JSEncrypt.prototype.getPrivateKey = function () {
5334         // Return the private representation of this key.
5335         return this.getKey().getPrivateKey();
5336     };
5337     /**
5338      * Returns the pem encoded representation of the private key
5339      * If the key doesn't exists a new key will be created
5340      * @returns {string} pem encoded representation of the private key WITHOUT header and footer
5341      * @public
5342      */
5343     JSEncrypt.prototype.getPrivateKeyB64 = function () {
5344         // Return the private representation of this key.
5345         return this.getKey().getPrivateBaseKeyB64();
5346     };
5347     /**
5348      * Returns the pem encoded representation of the public key
5349      * If the key doesn't exists a new key will be created
5350      * @returns {string} pem encoded representation of the public key WITH header and footer
5351      * @public
5352      */
5353     JSEncrypt.prototype.getPublicKey = function () {
5354         // Return the private representation of this key.
5355         return this.getKey().getPublicKey();
5356     };
5357     /**
5358      * Returns the pem encoded representation of the public key
5359      * If the key doesn't exists a new key will be created
5360      * @returns {string} pem encoded representation of the public key WITHOUT header and footer
5361      * @public
5362      */
5363     JSEncrypt.prototype.getPublicKeyB64 = function () {
5364         // Return the private representation of this key.
5365         return this.getKey().getPublicBaseKeyB64();
5366     };
5367     JSEncrypt.version = "3.0.0-rc.1";
5368     return JSEncrypt;
5369 }());
5370
5371 window.JSEncrypt = JSEncrypt;
5372
5373 exports.JSEncrypt = JSEncrypt;
5374 exports.default = JSEncrypt;
5375
5376 Object.defineProperty(exports, '__esModule', { value: true });
5377
5378 })));