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