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