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';
7 const crypto = require('crypto');
8 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
10 Math.random = function() {
11 const byteArray = new Uint32Array(1);
12 return (crypto.getRandomValues(byteArray))[0];
15 function int2char(n) {
16 return BI_RM.charAt(n);
18 //#region BIT_OPERATIONS
20 function op_and(x, y) {
24 function op_or(x, y) {
28 function op_xor(x, y) {
32 function op_andnot(x, y) {
35 // return index of lowest 1-bit in x, x < 2^31
41 if ((x & 0xffff) == 0) {
45 if ((x & 0xff) == 0) {
62 // return number of 1 bits in x
71 //#endregion BIT_OPERATIONS
73 var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
79 for (i = 0; i + 3 <= h.length; i += 3) {
80 c = parseInt(h.substring(i, i + 3), 16);
81 ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
83 if (i + 1 == h.length) {
84 c = parseInt(h.substring(i, i + 1), 16);
85 ret += b64map.charAt(c << 2);
87 else if (i + 2 == h.length) {
88 c = parseInt(h.substring(i, i + 2), 16);
89 ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
91 while ((ret.length & 3) > 0) {
96 // convert a base64 string to hex
97 function b64tohex(s) {
100 var k = 0; // b64 state, 0-3
102 for (i = 0; i < s.length; ++i) {
103 if (s.charAt(i) == b64pad) {
106 var v = b64map.indexOf(s.charAt(i));
111 ret += int2char(v >> 2);
116 ret += int2char((slop << 2) | (v >> 4));
121 ret += int2char(slop);
122 ret += int2char(v >> 2);
127 ret += int2char((slop << 2) | (v >> 4));
128 ret += int2char(v & 0xf);
133 ret += int2char(slop << 2);
138 /*! *****************************************************************************
139 Copyright (c) Microsoft Corporation. All rights reserved.
140 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
141 this file except in compliance with the License. You may obtain a copy of the
142 License at http://www.apache.org/licenses/LICENSE-2.0
143 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
144 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
145 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
146 MERCHANTABLITY OR NON-INFRINGEMENT.
147 See the Apache Version 2.0 License for specific language governing permissions
148 and limitations under the License.
149 ***************************************************************************** */
150 /* global Reflect, Promise */
152 var extendStatics = function(d, b) {
153 extendStatics = Object.setPrototypeOf ||
154 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
155 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
156 return extendStatics(d, b);
159 function __extends(d, b) {
161 function __() { this.constructor = d; }
162 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
165 // Hex JavaScript decoder
166 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
167 // Permission to use, copy, modify, and/or distribute this software for any
168 // purpose with or without fee is hereby granted, provided that the above
169 // copyright notice and this permission notice appear in all copies.
171 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
172 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
173 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
174 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
175 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
176 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
177 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
178 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
181 decode: function (a) {
183 if (decoder === undefined) {
184 var hex = "0123456789ABCDEF";
185 var ignore = " \f\n\r\t\u00A0\u2028\u2029";
187 for (i = 0; i < 16; ++i) {
188 decoder[hex.charAt(i)] = i;
190 hex = hex.toLowerCase();
191 for (i = 10; i < 16; ++i) {
192 decoder[hex.charAt(i)] = i;
194 for (i = 0; i < ignore.length; ++i) {
195 decoder[ignore.charAt(i)] = -1;
201 for (i = 0; i < a.length; ++i) {
210 if (c === undefined) {
211 throw new Error("Illegal character at offset " + i);
214 if (++char_count >= 2) {
215 out[out.length] = bits;
224 throw new Error("Hex encoding incomplete: 4 bits missing");
230 // Base64 JavaScript decoder
231 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
232 // Permission to use, copy, modify, and/or distribute this software for any
233 // purpose with or without fee is hereby granted, provided that the above
234 // copyright notice and this permission notice appear in all copies.
236 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
237 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
238 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
239 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
240 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
241 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
242 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
243 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
246 decode: function (a) {
248 if (decoder$1 === undefined) {
249 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
250 var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
251 decoder$1 = Object.create(null);
252 for (i = 0; i < 64; ++i) {
253 decoder$1[b64.charAt(i)] = i;
255 for (i = 0; i < ignore.length; ++i) {
256 decoder$1[ignore.charAt(i)] = -1;
262 for (i = 0; i < a.length; ++i) {
271 if (c === undefined) {
272 throw new Error("Illegal character at offset " + i);
275 if (++char_count >= 4) {
276 out[out.length] = (bits >> 16);
277 out[out.length] = (bits >> 8) & 0xFF;
278 out[out.length] = bits & 0xFF;
286 switch (char_count) {
288 throw new Error("Base64 encoding incomplete: at least 2 bits missing");
290 out[out.length] = (bits >> 10);
293 out[out.length] = (bits >> 16);
294 out[out.length] = (bits >> 8) & 0xFF;
299 re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
300 unarmor: function (a) {
301 var m = Base64.re.exec(a);
310 throw new Error("RegExp out of sync");
313 return Base64.decode(a);
317 // Big integer base-10 printing library
318 // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
319 // Permission to use, copy, modify, and/or distribute this software for any
320 // purpose with or without fee is hereby granted, provided that the above
321 // copyright notice and this permission notice appear in all copies.
323 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
324 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
325 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
326 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
327 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
328 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
329 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
330 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
331 var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
332 var Int10 = /** @class */ (function () {
333 function Int10(value) {
334 this.buf = [+value || 0];
336 Int10.prototype.mulAdd = function (m, c) {
342 for (i = 0; i < l; ++i) {
357 Int10.prototype.sub = function (c) {
363 for (i = 0; i < l; ++i) {
374 while (b[b.length - 1] === 0) {
378 Int10.prototype.toString = function (base) {
379 if ((base || 10) != 10) {
380 throw new Error("only base 10 is supported");
383 var s = b[b.length - 1].toString();
384 for (var i = b.length - 2; i >= 0; --i) {
385 s += (max + b[i]).toString().substring(1);
389 Int10.prototype.valueOf = function () {
392 for (var i = b.length - 1; i >= 0; --i) {
397 Int10.prototype.simplify = function () {
399 return (b.length == 1) ? b[0] : this;
404 // ASN.1 JavaScript decoder
405 var ellipsis = "\u2026";
406 var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
407 var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
408 function stringCut(str, len) {
409 if (str.length > len) {
410 str = str.substring(0, len) + ellipsis;
414 var Stream = /** @class */ (function () {
415 function Stream(enc, pos) {
416 this.hexDigits = "0123456789ABCDEF";
417 if (enc instanceof Stream) {
422 // enc should be an array or a binary string
427 Stream.prototype.get = function (pos) {
428 if (pos === undefined) {
431 if (pos >= this.enc.length) {
432 throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
434 return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
436 Stream.prototype.hexByte = function (b) {
437 return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
439 Stream.prototype.hexDump = function (start, end, raw) {
441 for (var i = start; i < end; ++i) {
442 s += this.hexByte(this.get(i));
458 Stream.prototype.isASCII = function (start, end) {
459 for (var i = start; i < end; ++i) {
461 if (c < 32 || c > 176) {
467 Stream.prototype.parseStringISO = function (start, end) {
469 for (var i = start; i < end; ++i) {
470 s += String.fromCharCode(this.get(i));
474 Stream.prototype.parseStringUTF = function (start, end) {
476 for (var i = start; i < end;) {
477 var c = this.get(i++);
479 s += String.fromCharCode(c);
481 else if ((c > 191) && (c < 224)) {
482 s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
485 s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
490 Stream.prototype.parseStringBMP = function (start, end) {
494 for (var i = start; i < end;) {
497 str += String.fromCharCode((hi << 8) | lo);
501 Stream.prototype.parseTime = function (start, end, shortYear) {
502 var s = this.parseStringISO(start, end);
503 var m = (shortYear ? reTimeS : reTimeL).exec(s);
505 return "Unrecognized time: " + s;
508 // to avoid querying the timer, use the fixed range [1970, 2069]
509 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
511 m[1] += (+m[1] < 70) ? 2000 : 1900;
513 s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
534 Stream.prototype.parseInteger = function (start, end) {
535 var v = this.get(start);
537 var pad = neg ? 255 : 0;
540 // skip unuseful bits (not allowed in DER)
541 while (v == pad && ++start < end) {
548 // show bit length of huge integers
552 while (((+s ^ pad) & 0x80) == 0) {
556 s = "(" + len + " bit)\n";
558 // decode the integer
562 var n = new Int10(v);
563 for (var i = start + 1; i < end; ++i) {
564 n.mulAdd(256, this.get(i));
566 return s + n.toString();
568 Stream.prototype.parseBitString = function (start, end, maxLength) {
569 var unusedBit = this.get(start);
570 var lenBit = ((end - start - 1) << 3) - unusedBit;
571 var intro = "(" + lenBit + " bit)\n";
573 for (var i = start + 1; i < end; ++i) {
575 var skip = (i == end - 1) ? unusedBit : 0;
576 for (var j = 7; j >= skip; --j) {
577 s += (b >> j) & 1 ? "1" : "0";
579 if (s.length > maxLength) {
580 return intro + stringCut(s, maxLength);
585 Stream.prototype.parseOctetString = function (start, end, maxLength) {
586 if (this.isASCII(start, end)) {
587 return stringCut(this.parseStringISO(start, end), maxLength);
589 var len = end - start;
590 var s = "(" + len + " byte)\n";
591 maxLength /= 2; // we work in bytes
592 if (len > maxLength) {
593 end = start + maxLength;
595 for (var i = start; i < end; ++i) {
596 s += this.hexByte(this.get(i));
598 if (len > maxLength) {
603 Stream.prototype.parseOID = function (start, end, maxLength) {
607 for (var i = start; i < end; ++i) {
609 n.mulAdd(128, v & 0x7F);
611 if (!(v & 0x80)) { // finished
614 if (n instanceof Int10) {
616 s = "2." + n.toString();
619 var m = n < 80 ? n < 40 ? 0 : 1 : 2;
620 s = m + "." + (n - m * 40);
624 s += "." + n.toString();
626 if (s.length > maxLength) {
627 return stringCut(s, maxLength);
640 var ASN1 = /** @class */ (function () {
641 function ASN1(stream, header, length, tag, sub) {
642 if (!(tag instanceof ASN1Tag)) {
643 throw new Error("Invalid tag value.");
645 this.stream = stream;
646 this.header = header;
647 this.length = length;
651 ASN1.prototype.typeName = function () {
652 switch (this.tag.tagClass) {
654 switch (this.tag.tagNumber) {
664 return "OCTET_STRING";
668 return "OBJECT_IDENTIFIER";
670 return "ObjectDescriptor";
678 return "EMBEDDED_PDV";
686 return "NumericString";
688 return "PrintableString"; // ASCII subset
690 return "TeletexString"; // aka T61String
692 return "VideotexString";
694 return "IA5String"; // ASCII
698 return "GeneralizedTime";
700 return "GraphicString";
702 return "VisibleString"; // ASCII subset
704 return "GeneralString";
706 return "UniversalString";
710 return "Universal_" + this.tag.tagNumber.toString();
712 return "Application_" + this.tag.tagNumber.toString();
714 return "[" + this.tag.tagNumber.toString() + "]"; // Context
716 return "Private_" + this.tag.tagNumber.toString();
719 ASN1.prototype.content = function (maxLength) {
720 if (this.tag === undefined) {
723 if (maxLength === undefined) {
724 maxLength = Infinity;
726 var content = this.posContent();
727 var len = Math.abs(this.length);
728 if (!this.tag.isUniversal()) {
729 if (this.sub !== null) {
730 return "(" + this.sub.length + " elem)";
732 return this.stream.parseOctetString(content, content + len, maxLength);
734 switch (this.tag.tagNumber) {
735 case 0x01: // BOOLEAN
736 return (this.stream.get(content) === 0) ? "false" : "true";
737 case 0x02: // INTEGER
738 return this.stream.parseInteger(content, content + len);
739 case 0x03: // BIT_STRING
740 return this.sub ? "(" + this.sub.length + " elem)" :
741 this.stream.parseBitString(content, content + len, maxLength);
742 case 0x04: // OCTET_STRING
743 return this.sub ? "(" + this.sub.length + " elem)" :
744 this.stream.parseOctetString(content, content + len, maxLength);
745 // case 0x05: // NULL
746 case 0x06: // OBJECT_IDENTIFIER
747 return this.stream.parseOID(content, content + len, maxLength);
748 // case 0x07: // ObjectDescriptor
749 // case 0x08: // EXTERNAL
750 // case 0x09: // REAL
751 // case 0x0A: // ENUMERATED
752 // case 0x0B: // EMBEDDED_PDV
753 case 0x10: // SEQUENCE
755 if (this.sub !== null) {
756 return "(" + this.sub.length + " elem)";
761 case 0x0C: // UTF8String
762 return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
763 case 0x12: // NumericString
764 case 0x13: // PrintableString
765 case 0x14: // TeletexString
766 case 0x15: // VideotexString
767 case 0x16: // IA5String
768 // case 0x19: // GraphicString
769 case 0x1A: // VisibleString
770 // case 0x1B: // GeneralString
771 // case 0x1C: // UniversalString
772 return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
773 case 0x1E: // BMPString
774 return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
775 case 0x17: // UTCTime
776 case 0x18: // GeneralizedTime
777 return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
781 ASN1.prototype.toString = function () {
782 return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
784 ASN1.prototype.toPrettyString = function (indent) {
785 if (indent === undefined) {
788 var s = indent + this.typeName() + " @" + this.stream.pos;
789 if (this.length >= 0) {
793 if (this.tag.tagConstructed) {
794 s += " (constructed)";
796 else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
797 s += " (encapsulates)";
800 if (this.sub !== null) {
802 for (var i = 0, max = this.sub.length; i < max; ++i) {
803 s += this.sub[i].toPrettyString(indent);
808 ASN1.prototype.posStart = function () {
809 return this.stream.pos;
811 ASN1.prototype.posContent = function () {
812 return this.stream.pos + this.header;
814 ASN1.prototype.posEnd = function () {
815 return this.stream.pos + this.header + Math.abs(this.length);
817 ASN1.prototype.toHexString = function () {
818 return this.stream.hexDump(this.posStart(), this.posEnd(), true);
820 ASN1.decodeLength = function (stream) {
821 var buf = stream.get();
822 var len = buf & 0x7F;
826 // no reason to use Int10, as it would be a huge buffer anyways
828 throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
834 for (var i = 0; i < len; ++i) {
835 buf = (buf * 256) + stream.get();
840 * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
844 ASN1.prototype.getHexStringValue = function () {
845 var hexString = this.toHexString();
846 var offset = this.header * 2;
847 var length = this.length * 2;
848 return hexString.substr(offset, length);
850 ASN1.decode = function (str) {
852 if (!(str instanceof Stream)) {
853 stream = new Stream(str, 0);
858 var streamStart = new Stream(stream);
859 var tag = new ASN1Tag(stream);
860 var len = ASN1.decodeLength(stream);
861 var start = stream.pos;
862 var header = start - streamStart.pos;
864 var getSub = function () {
868 var end = start + len;
869 while (stream.pos < end) {
870 ret[ret.length] = ASN1.decode(stream);
872 if (stream.pos != end) {
873 throw new Error("Content size is not correct for container starting at offset " + start);
880 var s = ASN1.decode(stream);
886 len = start - stream.pos; // undefined lengths are represented as negative values
889 throw new Error("Exception while decoding undefined length content: " + e);
894 if (tag.tagConstructed) {
895 // must have valid content
898 else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
899 // sometimes BitString and OctetString are used to encapsulate ASN.1
901 if (tag.tagNumber == 0x03) {
902 if (stream.get() != 0) {
903 throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
907 for (var i = 0; i < sub.length; ++i) {
908 if (sub[i].tag.isEOC()) {
909 throw new Error("EOC is not supposed to be actual content.");
914 // but silently ignore when they don't
920 throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
922 stream.pos = start + Math.abs(len);
924 return new ASN1(streamStart, header, len, tag, sub);
928 var ASN1Tag = /** @class */ (function () {
929 function ASN1Tag(stream) {
930 var buf = stream.get();
931 this.tagClass = buf >> 6;
932 this.tagConstructed = ((buf & 0x20) !== 0);
933 this.tagNumber = buf & 0x1F;
934 if (this.tagNumber == 0x1F) { // long tag
938 n.mulAdd(128, buf & 0x7F);
939 } while (buf & 0x80);
940 this.tagNumber = n.simplify();
943 ASN1Tag.prototype.isUniversal = function () {
944 return this.tagClass === 0x00;
946 ASN1Tag.prototype.isEOC = function () {
947 return this.tagClass === 0x00 && this.tagNumber === 0x00;
952 // Copyright (c) 2005 Tom Wu
955 // JavaScript engine analysis
956 var canary = 0xdeadbeefcafe;
957 var j_lm = ((canary & 0xffffff) == 0xefcafe);
959 var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
960 var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
962 // (public) Constructor
963 var BigInteger = /** @class */ (function () {
964 function BigInteger(a, b, c) {
966 if ("number" == typeof a) {
967 this.fromNumber(a, b, c);
969 else if (b == null && "string" != typeof a) {
970 this.fromString(a, 256);
973 this.fromString(a, b);
978 // BigInteger.prototype.toString = bnToString;
979 // (public) return string representation in given radix
980 BigInteger.prototype.toString = function (b) {
982 return "-" + this.negate().toString(b);
1001 return this.toRadix(b);
1003 var km = (1 << k) - 1;
1008 var p = this.DB - (i * this.DB) % k;
1010 if (p < this.DB && (d = this[i] >> p) > 0) {
1016 d = (this[i] & ((1 << p) - 1)) << (k - p);
1017 d |= this[--i] >> (p += this.DB - k);
1020 d = (this[i] >> (p -= k)) & km;
1036 // BigInteger.prototype.negate = bnNegate;
1038 BigInteger.prototype.negate = function () {
1040 BigInteger.ZERO.subTo(this, r);
1043 // BigInteger.prototype.abs = bnAbs;
1045 BigInteger.prototype.abs = function () {
1046 return (this.s < 0) ? this.negate() : this;
1048 // BigInteger.prototype.compareTo = bnCompareTo;
1049 // (public) return + if this > a, - if this < a, 0 if equal
1050 BigInteger.prototype.compareTo = function (a) {
1051 var r = this.s - a.s;
1058 return (this.s < 0) ? -r : r;
1061 if ((r = this[i] - a[i]) != 0) {
1067 // BigInteger.prototype.bitLength = bnBitLength;
1068 // (public) return the number of bits in "this"
1069 BigInteger.prototype.bitLength = function () {
1073 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
1075 // BigInteger.prototype.mod = bnMod;
1076 // (public) this mod a
1077 BigInteger.prototype.mod = function (a) {
1079 this.abs().divRemTo(a, null, r);
1080 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
1085 // BigInteger.prototype.modPowInt = bnModPowInt;
1086 // (public) this^e % m, 0 <= e < 2^32
1087 BigInteger.prototype.modPowInt = function (e, m) {
1089 if (e < 256 || m.isEven()) {
1093 z = new Montgomery(m);
1095 return this.exp(e, z);
1097 // BigInteger.prototype.clone = bnClone;
1099 BigInteger.prototype.clone = function () {
1104 // BigInteger.prototype.intValue = bnIntValue;
1105 // (public) return value as integer
1106 BigInteger.prototype.intValue = function () {
1109 return this[0] - this.DV;
1111 else if (this.t == 0) {
1115 else if (this.t == 1) {
1118 else if (this.t == 0) {
1121 // assumes 16 < DB < 32
1122 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
1124 // BigInteger.prototype.byteValue = bnByteValue;
1125 // (public) return value as byte
1126 BigInteger.prototype.byteValue = function () {
1127 return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
1129 // BigInteger.prototype.shortValue = bnShortValue;
1130 // (public) return value as short (assumes DB>=16)
1131 BigInteger.prototype.shortValue = function () {
1132 return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
1134 // BigInteger.prototype.signum = bnSigNum;
1135 // (public) 0 if this == 0, 1 if this > 0
1136 BigInteger.prototype.signum = function () {
1140 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
1147 // BigInteger.prototype.toByteArray = bnToByteArray;
1148 // (public) convert to bigendian byte array
1149 BigInteger.prototype.toByteArray = function () {
1153 var p = this.DB - (i * this.DB) % 8;
1157 if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
1158 r[k++] = d | (this.s << (this.DB - p));
1162 d = (this[i] & ((1 << p) - 1)) << (8 - p);
1163 d |= this[--i] >> (p += this.DB - 8);
1166 d = (this[i] >> (p -= 8)) & 0xff;
1172 if ((d & 0x80) != 0) {
1175 if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
1178 if (k > 0 || d != this.s) {
1185 // BigInteger.prototype.equals = bnEquals;
1186 BigInteger.prototype.equals = function (a) {
1187 return (this.compareTo(a) == 0);
1189 // BigInteger.prototype.min = bnMin;
1190 BigInteger.prototype.min = function (a) {
1191 return (this.compareTo(a) < 0) ? this : a;
1193 // BigInteger.prototype.max = bnMax;
1194 BigInteger.prototype.max = function (a) {
1195 return (this.compareTo(a) > 0) ? this : a;
1197 // BigInteger.prototype.and = bnAnd;
1198 BigInteger.prototype.and = function (a) {
1200 this.bitwiseTo(a, op_and, r);
1203 // BigInteger.prototype.or = bnOr;
1204 BigInteger.prototype.or = function (a) {
1206 this.bitwiseTo(a, op_or, r);
1209 // BigInteger.prototype.xor = bnXor;
1210 BigInteger.prototype.xor = function (a) {
1212 this.bitwiseTo(a, op_xor, r);
1215 // BigInteger.prototype.andNot = bnAndNot;
1216 BigInteger.prototype.andNot = function (a) {
1218 this.bitwiseTo(a, op_andnot, r);
1221 // BigInteger.prototype.not = bnNot;
1223 BigInteger.prototype.not = function () {
1225 for (var i = 0; i < this.t; ++i) {
1226 r[i] = this.DM & ~this[i];
1232 // BigInteger.prototype.shiftLeft = bnShiftLeft;
1233 // (public) this << n
1234 BigInteger.prototype.shiftLeft = function (n) {
1237 this.rShiftTo(-n, r);
1240 this.lShiftTo(n, r);
1244 // BigInteger.prototype.shiftRight = bnShiftRight;
1245 // (public) this >> n
1246 BigInteger.prototype.shiftRight = function (n) {
1249 this.lShiftTo(-n, r);
1252 this.rShiftTo(n, r);
1256 // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
1257 // (public) returns index of lowest 1-bit (or -1 if none)
1258 BigInteger.prototype.getLowestSetBit = function () {
1259 for (var i = 0; i < this.t; ++i) {
1261 return i * this.DB + lbit(this[i]);
1265 return this.t * this.DB;
1269 // BigInteger.prototype.bitCount = bnBitCount;
1270 // (public) return number of set bits
1271 BigInteger.prototype.bitCount = function () {
1273 var x = this.s & this.DM;
1274 for (var i = 0; i < this.t; ++i) {
1275 r += cbit(this[i] ^ x);
1279 // BigInteger.prototype.testBit = bnTestBit;
1280 // (public) true iff nth bit is set
1281 BigInteger.prototype.testBit = function (n) {
1282 var j = Math.floor(n / this.DB);
1284 return (this.s != 0);
1286 return ((this[j] & (1 << (n % this.DB))) != 0);
1288 // BigInteger.prototype.setBit = bnSetBit;
1289 // (public) this | (1<<n)
1290 BigInteger.prototype.setBit = function (n) {
1291 return this.changeBit(n, op_or);
1293 // BigInteger.prototype.clearBit = bnClearBit;
1294 // (public) this & ~(1<<n)
1295 BigInteger.prototype.clearBit = function (n) {
1296 return this.changeBit(n, op_andnot);
1298 // BigInteger.prototype.flipBit = bnFlipBit;
1299 // (public) this ^ (1<<n)
1300 BigInteger.prototype.flipBit = function (n) {
1301 return this.changeBit(n, op_xor);
1303 // BigInteger.prototype.add = bnAdd;
1304 // (public) this + a
1305 BigInteger.prototype.add = function (a) {
1310 // BigInteger.prototype.subtract = bnSubtract;
1311 // (public) this - a
1312 BigInteger.prototype.subtract = function (a) {
1317 // BigInteger.prototype.multiply = bnMultiply;
1318 // (public) this * a
1319 BigInteger.prototype.multiply = function (a) {
1321 this.multiplyTo(a, r);
1324 // BigInteger.prototype.divide = bnDivide;
1325 // (public) this / a
1326 BigInteger.prototype.divide = function (a) {
1328 this.divRemTo(a, r, null);
1331 // BigInteger.prototype.remainder = bnRemainder;
1332 // (public) this % a
1333 BigInteger.prototype.remainder = function (a) {
1335 this.divRemTo(a, null, r);
1338 // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
1339 // (public) [this/a,this%a]
1340 BigInteger.prototype.divideAndRemainder = function (a) {
1343 this.divRemTo(a, q, r);
1346 // BigInteger.prototype.modPow = bnModPow;
1347 // (public) this^e % m (HAC 14.85)
1348 BigInteger.prototype.modPow = function (e, m) {
1349 var i = e.bitLength();
1374 else if (m.isEven()) {
1378 z = new Montgomery(m);
1384 var km = (1 << k) - 1;
1385 g[1] = z.convert(this);
1391 z.mulTo(g2, g[n - 2], g[n]);
1400 i = nbits(e[j]) - 1;
1403 w = (e[j] >> (i - k1)) & km;
1406 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
1408 w |= e[j - 1] >> (this.DB + i - k1);
1412 while ((w & 1) == 0) {
1420 if (is1) { // ret == 1, don't bother squaring or multiplying it
1438 z.mulTo(r2, g[w], r);
1440 while (j >= 0 && (e[j] & (1 << i)) == 0) {
1453 // BigInteger.prototype.modInverse = bnModInverse;
1454 // (public) 1/this % m (HAC 14.61)
1455 BigInteger.prototype.modInverse = function (m) {
1456 var ac = m.isEven();
1457 if ((this.isEven() && ac) || m.signum() == 0) {
1458 return BigInteger.ZERO;
1461 var v = this.clone();
1466 while (u.signum() != 0) {
1467 while (u.isEven()) {
1470 if (!a.isEven() || !b.isEven()) {
1476 else if (!b.isEven()) {
1481 while (v.isEven()) {
1484 if (!c.isEven() || !d.isEven()) {
1490 else if (!d.isEven()) {
1495 if (u.compareTo(v) >= 0) {
1510 if (v.compareTo(BigInteger.ONE) != 0) {
1511 return BigInteger.ZERO;
1513 if (d.compareTo(m) >= 0) {
1514 return d.subtract(m);
1516 if (d.signum() < 0) {
1522 if (d.signum() < 0) {
1529 // BigInteger.prototype.pow = bnPow;
1531 BigInteger.prototype.pow = function (e) {
1532 return this.exp(e, new NullExp());
1534 // BigInteger.prototype.gcd = bnGCD;
1535 // (public) gcd(this,a) (HAC 14.54)
1536 BigInteger.prototype.gcd = function (a) {
1537 var x = (this.s < 0) ? this.negate() : this.clone();
1538 var y = (a.s < 0) ? a.negate() : a.clone();
1539 if (x.compareTo(y) < 0) {
1544 var i = x.getLowestSetBit();
1545 var g = y.getLowestSetBit();
1556 while (x.signum() > 0) {
1557 if ((i = x.getLowestSetBit()) > 0) {
1560 if ((i = y.getLowestSetBit()) > 0) {
1563 if (x.compareTo(y) >= 0) {
1577 // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
1578 // (public) test primality with certainty >= 1-.5^t
1579 BigInteger.prototype.isProbablePrime = function (t) {
1582 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
1583 for (i = 0; i < lowprimes.length; ++i) {
1584 if (x[0] == lowprimes[i]) {
1594 while (i < lowprimes.length) {
1595 var m = lowprimes[i];
1597 while (j < lowprimes.length && m < lplim) {
1598 m *= lowprimes[j++];
1602 if (m % lowprimes[i++] == 0) {
1607 return x.millerRabin(t);
1611 // BigInteger.prototype.copyTo = bnpCopyTo;
1612 // (protected) copy this to r
1613 BigInteger.prototype.copyTo = function (r) {
1614 for (var i = this.t - 1; i >= 0; --i) {
1620 // BigInteger.prototype.fromInt = bnpFromInt;
1621 // (protected) set from integer value x, -DV <= x < DV
1622 BigInteger.prototype.fromInt = function (x) {
1624 this.s = (x < 0) ? -1 : 0;
1629 this[0] = x + this.DV;
1635 // BigInteger.prototype.fromString = bnpFromString;
1636 // (protected) set from string and radix
1637 BigInteger.prototype.fromString = function (s, b) {
1645 else if (b == 256) {
1659 this.fromRadix(s, b);
1668 var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
1670 if (s.charAt(i) == "-") {
1679 else if (sh + k > this.DB) {
1680 this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
1681 this[this.t++] = (x >> (this.DB - sh));
1684 this[this.t - 1] |= x << sh;
1687 if (sh >= this.DB) {
1691 if (k == 8 && ((+s[0]) & 0x80) != 0) {
1694 this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
1699 BigInteger.ZERO.subTo(this, this);
1702 // BigInteger.prototype.clamp = bnpClamp;
1703 // (protected) clamp off excess high words
1704 BigInteger.prototype.clamp = function () {
1705 var c = this.s & this.DM;
1706 while (this.t > 0 && this[this.t - 1] == c) {
1710 // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
1711 // (protected) r = this << n*DB
1712 BigInteger.prototype.dlShiftTo = function (n, r) {
1714 for (i = this.t - 1; i >= 0; --i) {
1717 for (i = n - 1; i >= 0; --i) {
1723 // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
1724 // (protected) r = this >> n*DB
1725 BigInteger.prototype.drShiftTo = function (n, r) {
1726 for (var i = n; i < this.t; ++i) {
1729 r.t = Math.max(this.t - n, 0);
1732 // BigInteger.prototype.lShiftTo = bnpLShiftTo;
1733 // (protected) r = this << n
1734 BigInteger.prototype.lShiftTo = function (n, r) {
1735 var bs = n % this.DB;
1736 var cbs = this.DB - bs;
1737 var bm = (1 << cbs) - 1;
1738 var ds = Math.floor(n / this.DB);
1739 var c = (this.s << bs) & this.DM;
1740 for (var i = this.t - 1; i >= 0; --i) {
1741 r[i + ds + 1] = (this[i] >> cbs) | c;
1742 c = (this[i] & bm) << bs;
1744 for (var i = ds - 1; i >= 0; --i) {
1748 r.t = this.t + ds + 1;
1752 // BigInteger.prototype.rShiftTo = bnpRShiftTo;
1753 // (protected) r = this >> n
1754 BigInteger.prototype.rShiftTo = function (n, r) {
1756 var ds = Math.floor(n / this.DB);
1761 var bs = n % this.DB;
1762 var cbs = this.DB - bs;
1763 var bm = (1 << bs) - 1;
1764 r[0] = this[ds] >> bs;
1765 for (var i = ds + 1; i < this.t; ++i) {
1766 r[i - ds - 1] |= (this[i] & bm) << cbs;
1767 r[i - ds] = this[i] >> bs;
1770 r[this.t - ds - 1] |= (this.s & bm) << cbs;
1775 // BigInteger.prototype.subTo = bnpSubTo;
1776 // (protected) r = this - a
1777 BigInteger.prototype.subTo = function (a, r) {
1780 var m = Math.min(a.t, this.t);
1782 c += this[i] - a[i];
1783 r[i++] = c & this.DM;
1788 while (i < this.t) {
1790 r[i++] = c & this.DM;
1799 r[i++] = c & this.DM;
1804 r.s = (c < 0) ? -1 : 0;
1806 r[i++] = this.DV + c;
1814 // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
1815 // (protected) r = this * a, r != this,a (HAC 14.12)
1816 // "this" should be the larger one if appropriate.
1817 BigInteger.prototype.multiplyTo = function (a, r) {
1825 for (i = 0; i < y.t; ++i) {
1826 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
1830 if (this.s != a.s) {
1831 BigInteger.ZERO.subTo(r, r);
1834 // BigInteger.prototype.squareTo = bnpSquareTo;
1835 // (protected) r = this^2, r != this (HAC 14.16)
1836 BigInteger.prototype.squareTo = function (r) {
1838 var i = r.t = 2 * x.t;
1842 for (i = 0; i < x.t - 1; ++i) {
1843 var c = x.am(i, x[i], r, 2 * i, 0, 1);
1844 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
1850 r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
1855 // BigInteger.prototype.divRemTo = bnpDivRemTo;
1856 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
1857 // r != q, this != m. q or r may be null.
1858 BigInteger.prototype.divRemTo = function (m, q, r) {
1863 var pt = this.abs();
1879 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
1881 pm.lShiftTo(nsh, y);
1882 pt.lShiftTo(nsh, r);
1893 var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
1894 var d1 = this.FV / yt;
1895 var d2 = (1 << this.F1) / yt;
1896 var e = 1 << this.F2;
1899 var t = (q == null) ? nbi() : q;
1901 if (r.compareTo(t) >= 0) {
1905 BigInteger.ONE.dlShiftTo(ys, t);
1906 t.subTo(y, y); // "negative" y so we can replace sub with am later
1911 // Estimate quotient digit
1912 var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
1913 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
1916 while (r[i] < --qd) {
1924 BigInteger.ZERO.subTo(q, q);
1931 } // Denormalize remainder
1933 BigInteger.ZERO.subTo(r, r);
1936 // BigInteger.prototype.invDigit = bnpInvDigit;
1937 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
1941 // xy(2-xy) = (1+km)(1-km)
1942 // x[y(2-xy)] = 1-k^2m^2
1943 // x[y(2-xy)] == 1 (mod m^2)
1944 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
1945 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
1946 // JS multiply "overflows" differently from C/C++, so care is needed here.
1947 BigInteger.prototype.invDigit = function () {
1955 var y = x & 3; // y == 1/x mod 2^2
1956 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
1957 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
1958 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
1959 // last step - calculate inverse mod DV directly;
1960 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
1961 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
1962 // we really want the negative inverse, and -DV < y < DV
1963 return (y > 0) ? this.DV - y : -y;
1965 // BigInteger.prototype.isEven = bnpIsEven;
1966 // (protected) true iff this is even
1967 BigInteger.prototype.isEven = function () {
1968 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
1970 // BigInteger.prototype.exp = bnpExp;
1971 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
1972 BigInteger.prototype.exp = function (e, z) {
1973 if (e > 0xffffffff || e < 1) {
1974 return BigInteger.ONE;
1978 var g = z.convert(this);
1979 var i = nbits(e) - 1;
1983 if ((e & (1 << i)) > 0) {
1994 // BigInteger.prototype.chunkSize = bnpChunkSize;
1995 // (protected) return x s.t. r^x < DV
1996 BigInteger.prototype.chunkSize = function (r) {
1997 return Math.floor(Math.LN2 * this.DB / Math.log(r));
1999 // BigInteger.prototype.toRadix = bnpToRadix;
2000 // (protected) convert to radix string
2001 BigInteger.prototype.toRadix = function (b) {
2005 if (this.signum() == 0 || b < 2 || b > 36) {
2008 var cs = this.chunkSize(b);
2009 var a = Math.pow(b, cs);
2014 this.divRemTo(d, y, z);
2015 while (y.signum() > 0) {
2016 r = (a + z.intValue()).toString(b).substr(1) + r;
2017 y.divRemTo(d, y, z);
2019 return z.intValue().toString(b) + r;
2021 // BigInteger.prototype.fromRadix = bnpFromRadix;
2022 // (protected) convert from radix string
2023 BigInteger.prototype.fromRadix = function (s, b) {
2028 var cs = this.chunkSize(b);
2029 var d = Math.pow(b, cs);
2033 for (var i = 0; i < s.length; ++i) {
2034 var x = intAt(s, i);
2036 if (s.charAt(i) == "-" && this.signum() == 0) {
2044 this.dAddOffset(w, 0);
2050 this.dMultiply(Math.pow(b, j));
2051 this.dAddOffset(w, 0);
2054 BigInteger.ZERO.subTo(this, this);
2057 // BigInteger.prototype.fromNumber = bnpFromNumber;
2058 // (protected) alternate constructor
2059 BigInteger.prototype.fromNumber = function (a, b, c) {
2060 if ("number" == typeof b) {
2061 // new BigInteger(int,int,RNG)
2066 this.fromNumber(a, c);
2067 if (!this.testBit(a - 1)) {
2069 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2071 if (this.isEven()) {
2072 this.dAddOffset(1, 0);
2074 while (!this.isProbablePrime(b)) {
2075 this.dAddOffset(2, 0);
2076 if (this.bitLength() > a) {
2077 this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
2083 // new BigInteger(int,RNG)
2086 x.length = (a >> 3) + 1;
2089 x[0] &= ((1 << t) - 1);
2094 this.fromString(x, 256);
2097 // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
2098 // (protected) r = this op a (bitwise)
2099 BigInteger.prototype.bitwiseTo = function (a, op, r) {
2102 var m = Math.min(a.t, this.t);
2103 for (i = 0; i < m; ++i) {
2104 r[i] = op(this[i], a[i]);
2108 for (i = m; i < this.t; ++i) {
2109 r[i] = op(this[i], f);
2114 f = this.s & this.DM;
2115 for (i = m; i < a.t; ++i) {
2120 r.s = op(this.s, a.s);
2123 // BigInteger.prototype.changeBit = bnpChangeBit;
2124 // (protected) this op (1<<n)
2125 BigInteger.prototype.changeBit = function (n, op) {
2126 var r = BigInteger.ONE.shiftLeft(n);
2127 this.bitwiseTo(r, op, r);
2130 // BigInteger.prototype.addTo = bnpAddTo;
2131 // (protected) r = this + a
2132 BigInteger.prototype.addTo = function (a, r) {
2135 var m = Math.min(a.t, this.t);
2137 c += this[i] + a[i];
2138 r[i++] = c & this.DM;
2143 while (i < this.t) {
2145 r[i++] = c & this.DM;
2154 r[i++] = c & this.DM;
2159 r.s = (c < 0) ? -1 : 0;
2164 r[i++] = this.DV + c;
2169 // BigInteger.prototype.dMultiply = bnpDMultiply;
2170 // (protected) this *= n, this >= 0, 1 < n < DV
2171 BigInteger.prototype.dMultiply = function (n) {
2172 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
2176 // BigInteger.prototype.dAddOffset = bnpDAddOffset;
2177 // (protected) this += n << w words, this >= 0
2178 BigInteger.prototype.dAddOffset = function (n, w) {
2182 while (this.t <= w) {
2186 while (this[w] >= this.DV) {
2188 if (++w >= this.t) {
2194 // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
2195 // (protected) r = lower n words of "this * a", a.t <= n
2196 // "this" should be the larger one if appropriate.
2197 BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
2198 var i = Math.min(this.t + a.t, n);
2199 r.s = 0; // assumes a,this >= 0
2204 for (var j = r.t - this.t; i < j; ++i) {
2205 r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
2207 for (var j = Math.min(a.t, n); i < j; ++i) {
2208 this.am(0, a[i], r, i, 0, n - i);
2212 // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
2213 // (protected) r = "this * a" without lower n words, n > 0
2214 // "this" should be the larger one if appropriate.
2215 BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
2217 var i = r.t = this.t + a.t - n;
2218 r.s = 0; // assumes a,this >= 0
2222 for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
2223 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
2228 // BigInteger.prototype.modInt = bnpModInt;
2229 // (protected) this % n, n < 2^26
2230 BigInteger.prototype.modInt = function (n) {
2234 var d = this.DV % n;
2235 var r = (this.s < 0) ? n - 1 : 0;
2241 for (var i = this.t - 1; i >= 0; --i) {
2242 r = (d * r + this[i]) % n;
2248 // BigInteger.prototype.millerRabin = bnpMillerRabin;
2249 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
2250 BigInteger.prototype.millerRabin = function (t) {
2251 var n1 = this.subtract(BigInteger.ONE);
2252 var k = n1.getLowestSetBit();
2256 var r = n1.shiftRight(k);
2258 if (t > lowprimes.length) {
2259 t = lowprimes.length;
2262 for (var i = 0; i < t; ++i) {
2263 // Pick bases at random, instead of starting at 2
2264 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
2265 var y = a.modPow(r, this);
2266 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
2268 while (j++ < k && y.compareTo(n1) != 0) {
2269 y = y.modPowInt(2, this);
2270 if (y.compareTo(BigInteger.ONE) == 0) {
2274 if (y.compareTo(n1) != 0) {
2281 // BigInteger.prototype.square = bnSquare;
2283 BigInteger.prototype.square = function () {
2289 // Public API method
2290 BigInteger.prototype.gcda = function (a, callback) {
2291 var x = (this.s < 0) ? this.negate() : this.clone();
2292 var y = (a.s < 0) ? a.negate() : a.clone();
2293 if (x.compareTo(y) < 0) {
2298 var i = x.getLowestSetBit();
2299 var g = y.getLowestSetBit();
2311 // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
2312 var gcda1 = function () {
2313 if ((i = x.getLowestSetBit()) > 0) {
2316 if ((i = y.getLowestSetBit()) > 0) {
2319 if (x.compareTo(y) >= 0) {
2327 if (!(x.signum() > 0)) {
2331 setTimeout(function () { callback(y); }, 0); // escape
2334 setTimeout(gcda1, 0);
2337 setTimeout(gcda1, 10);
2339 // (protected) alternate constructor
2340 BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
2341 if ("number" == typeof b) {
2346 this.fromNumber(a, c);
2347 if (!this.testBit(a - 1)) {
2348 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2350 if (this.isEven()) {
2351 this.dAddOffset(1, 0);
2354 var bnpfn1_1 = function () {
2355 bnp_1.dAddOffset(2, 0);
2356 if (bnp_1.bitLength() > a) {
2357 bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
2359 if (bnp_1.isProbablePrime(b)) {
2360 setTimeout(function () { callback(); }, 0); // escape
2363 setTimeout(bnpfn1_1, 0);
2366 setTimeout(bnpfn1_1, 0);
2372 x.length = (a >> 3) + 1;
2375 x[0] &= ((1 << t) - 1);
2380 this.fromString(x, 256);
2387 var NullExp = /** @class */ (function () {
2388 function NullExp() {
2390 // NullExp.prototype.convert = nNop;
2391 NullExp.prototype.convert = function (x) {
2394 // NullExp.prototype.revert = nNop;
2395 NullExp.prototype.revert = function (x) {
2398 // NullExp.prototype.mulTo = nMulTo;
2399 NullExp.prototype.mulTo = function (x, y, r) {
2402 // NullExp.prototype.sqrTo = nSqrTo;
2403 NullExp.prototype.sqrTo = function (x, r) {
2408 // Modular reduction using "classic" algorithm
2409 var Classic = /** @class */ (function () {
2410 function Classic(m) {
2413 // Classic.prototype.convert = cConvert;
2414 Classic.prototype.convert = function (x) {
2415 if (x.s < 0 || x.compareTo(this.m) >= 0) {
2416 return x.mod(this.m);
2422 // Classic.prototype.revert = cRevert;
2423 Classic.prototype.revert = function (x) {
2426 // Classic.prototype.reduce = cReduce;
2427 Classic.prototype.reduce = function (x) {
2428 x.divRemTo(this.m, null, x);
2430 // Classic.prototype.mulTo = cMulTo;
2431 Classic.prototype.mulTo = function (x, y, r) {
2435 // Classic.prototype.sqrTo = cSqrTo;
2436 Classic.prototype.sqrTo = function (x, r) {
2443 //#region Montgomery
2444 // Montgomery reduction
2445 var Montgomery = /** @class */ (function () {
2446 function Montgomery(m) {
2448 this.mp = m.invDigit();
2449 this.mpl = this.mp & 0x7fff;
2450 this.mph = this.mp >> 15;
2451 this.um = (1 << (m.DB - 15)) - 1;
2454 // Montgomery.prototype.convert = montConvert;
2456 Montgomery.prototype.convert = function (x) {
2458 x.abs().dlShiftTo(this.m.t, r);
2459 r.divRemTo(this.m, null, r);
2460 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
2465 // Montgomery.prototype.revert = montRevert;
2467 Montgomery.prototype.revert = function (x) {
2473 // Montgomery.prototype.reduce = montReduce;
2474 // x = x/R mod m (HAC 14.32)
2475 Montgomery.prototype.reduce = function (x) {
2476 while (x.t <= this.mt2) {
2477 // pad x so am has enough room later
2480 for (var i = 0; i < this.m.t; ++i) {
2481 // faster way of calculating u0 = x[i]*mp mod DV
2482 var j = x[i] & 0x7fff;
2483 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
2484 // use am to combine the multiply-shift-add into one call
2486 x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
2488 while (x[j] >= x.DV) {
2494 x.drShiftTo(this.m.t, x);
2495 if (x.compareTo(this.m) >= 0) {
2499 // Montgomery.prototype.mulTo = montMulTo;
2500 // r = "xy/R mod m"; x,y != r
2501 Montgomery.prototype.mulTo = function (x, y, r) {
2505 // Montgomery.prototype.sqrTo = montSqrTo;
2506 // r = "x^2/R mod m"; x != r
2507 Montgomery.prototype.sqrTo = function (x, r) {
2513 //#endregion Montgomery
2515 // Barrett modular reduction
2516 var Barrett = /** @class */ (function () {
2517 function Barrett(m) {
2522 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
2523 this.mu = this.r2.divide(m);
2525 // Barrett.prototype.convert = barrettConvert;
2526 Barrett.prototype.convert = function (x) {
2527 if (x.s < 0 || x.t > 2 * this.m.t) {
2528 return x.mod(this.m);
2530 else if (x.compareTo(this.m) < 0) {
2540 // Barrett.prototype.revert = barrettRevert;
2541 Barrett.prototype.revert = function (x) {
2544 // Barrett.prototype.reduce = barrettReduce;
2545 // x = x mod m (HAC 14.42)
2546 Barrett.prototype.reduce = function (x) {
2547 x.drShiftTo(this.m.t - 1, this.r2);
2548 if (x.t > this.m.t + 1) {
2552 this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
2553 this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
2554 while (x.compareTo(this.r2) < 0) {
2555 x.dAddOffset(1, this.m.t + 1);
2557 x.subTo(this.r2, x);
2558 while (x.compareTo(this.m) >= 0) {
2562 // Barrett.prototype.mulTo = barrettMulTo;
2563 // r = x*y mod m; x,y != r
2564 Barrett.prototype.mulTo = function (x, y, r) {
2568 // Barrett.prototype.sqrTo = barrettSqrTo;
2569 // r = x^2 mod m; x != r
2570 Barrett.prototype.sqrTo = function (x, r) {
2577 //#endregion REDUCERS
2578 // return new, unset BigInteger
2579 function nbi() { return new BigInteger(null); }
2580 function parseBigInt(str, r) {
2581 return new BigInteger(str, r);
2583 // am: Compute w_j += (x*this_i), propagate carries,
2584 // c is initial carry, returns final carry.
2585 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
2586 // We need to select the fastest one that works in this environment.
2587 // am1: use a single mult and divide to get the high bits,
2588 // max digit bits should be 26 because
2589 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
2590 function am1(i, x, w, j, c, n) {
2592 var v = x * this[i++] + w[j] + c;
2593 c = Math.floor(v / 0x4000000);
2594 w[j++] = v & 0x3ffffff;
2598 // am2 avoids a big mult-and-extract completely.
2599 // Max digit bits should be <= 30 because we do bitwise ops
2600 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
2601 function am2(i, x, w, j, c, n) {
2602 var xl = x & 0x7fff;
2605 var l = this[i] & 0x7fff;
2606 var h = this[i++] >> 15;
2607 var m = xh * l + h * xl;
2608 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
2609 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
2610 w[j++] = l & 0x3fffffff;
2614 // Alternately, set max digit bits to 28 since some
2615 // browsers slow down when dealing with 32-bit numbers.
2616 function am3(i, x, w, j, c, n) {
2617 var xl = x & 0x3fff;
2620 var l = this[i] & 0x3fff;
2621 var h = this[i++] >> 14;
2622 var m = xh * l + h * xl;
2623 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
2624 c = (l >> 28) + (m >> 14) + xh * h;
2625 w[j++] = l & 0xfffffff;
2629 // if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
2630 // BigInteger.prototype.am = am2;
2633 // else if (j_lm && (navigator.appName != "Netscape")) {
2634 // BigInteger.prototype.am = am1;
2637 // else { // Mozilla/Netscape seems to prefer am3
2638 // BigInteger.prototype.am = am3;
2641 BigInteger.prototype.am = am1;
2644 BigInteger.prototype.DB = dbits;
2645 BigInteger.prototype.DM = ((1 << dbits) - 1);
2646 BigInteger.prototype.DV = (1 << dbits);
2648 BigInteger.prototype.FV = Math.pow(2, BI_FP);
2649 BigInteger.prototype.F1 = BI_FP - dbits;
2650 BigInteger.prototype.F2 = 2 * dbits - BI_FP;
2651 // Digit conversions
2655 rr = "0".charCodeAt(0);
2656 for (vv = 0; vv <= 9; ++vv) {
2659 rr = "a".charCodeAt(0);
2660 for (vv = 10; vv < 36; ++vv) {
2663 rr = "A".charCodeAt(0);
2664 for (vv = 10; vv < 36; ++vv) {
2667 function intAt(s, i) {
2668 var c = BI_RC[s.charCodeAt(i)];
2669 return (c == null) ? -1 : c;
2671 // return bigint initialized to value
2677 // returns bit length of the integer x
2681 if ((t = x >>> 16) != 0) {
2685 if ((t = x >> 8) != 0) {
2689 if ((t = x >> 4) != 0) {
2693 if ((t = x >> 2) != 0) {
2697 if ((t = x >> 1) != 0) {
2704 BigInteger.ZERO = nbv(0);
2705 BigInteger.ONE = nbv(1);
2707 // prng4.js - uses Arcfour as a PRNG
2708 var Arcfour = /** @class */ (function () {
2709 function Arcfour() {
2714 // Arcfour.prototype.init = ARC4init;
2715 // Initialize arcfour context from key, an array of ints, each from [0..255]
2716 Arcfour.prototype.init = function (key) {
2720 for (i = 0; i < 256; ++i) {
2724 for (i = 0; i < 256; ++i) {
2725 j = (j + this.S[i] + key[i % key.length]) & 255;
2727 this.S[i] = this.S[j];
2733 // Arcfour.prototype.next = ARC4next;
2734 Arcfour.prototype.next = function () {
2736 this.i = (this.i + 1) & 255;
2737 this.j = (this.j + this.S[this.i]) & 255;
2739 this.S[this.i] = this.S[this.j];
2741 return this.S[(t + this.S[this.i]) & 255];
2745 // Plug in your RNG constructor here
2746 function prng_newstate() {
2747 return new Arcfour();
2749 // Pool size must be a multiple of 4 and greater than 32.
2750 // An array of bytes the size of the pool will be passed to init()
2751 var rng_psize = 256;
2753 // Random number generator - requires a PRNG backend, e.g. prng4.js
2755 var rng_pool = null;
2757 // Initialize the pool with junk if needed.
2758 if (rng_pool == null) {
2762 if (window.crypto && window.crypto.getRandomValues) {
2763 // Extract entropy (2048 bits) from RNG if available
2764 var z = new Uint32Array(256);
2765 window.crypto.getRandomValues(z);
2766 for (t = 0; t < z.length; ++t) {
2767 rng_pool[rng_pptr++] = z[t] & 255;
2770 // Use mouse events for entropy, if we do not have enough entropy by the time
2771 // we need it, entropy will be generated by Math.random.
2772 var onMouseMoveListener_1 = function (ev) {
2773 this.count = this.count || 0;
2774 if (this.count >= 256 || rng_pptr >= rng_psize) {
2775 if (window.removeEventListener) {
2776 window.removeEventListener("mousemove", onMouseMoveListener_1, false);
2778 else if (window.detachEvent) {
2779 window.detachEvent("onmousemove", onMouseMoveListener_1);
2784 var mouseCoordinates = ev.x + ev.y;
2785 rng_pool[rng_pptr++] = mouseCoordinates & 255;
2789 // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
2792 if (window.addEventListener) {
2793 window.addEventListener("mousemove", onMouseMoveListener_1, false);
2795 else if (window.attachEvent) {
2796 window.attachEvent("onmousemove", onMouseMoveListener_1);
2799 function rng_get_byte() {
2800 if (rng_state == null) {
2801 rng_state = prng_newstate();
2802 // At this point, we may not have collected enough entropy. If not, fall back to Math.random
2803 while (rng_pptr < rng_psize) {
2804 var random = Math.floor(65536 * Math.random());
2805 rng_pool[rng_pptr++] = random & 255;
2807 rng_state.init(rng_pool);
2808 for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
2809 rng_pool[rng_pptr] = 0;
2813 // TODO: allow reseeding after first request
2814 return rng_state.next();
2816 var SecureRandom = /** @class */ (function () {
2817 function SecureRandom() {
2819 SecureRandom.prototype.nextBytes = function (ba) {
2820 for (var i = 0; i < ba.length; ++i) {
2821 ba[i] = rng_get_byte();
2824 return SecureRandom;
2827 // Depends on jsbn.js and rng.js
2828 // function linebrk(s,n) {
2831 // while(i + n < s.length) {
2832 // ret += s.substring(i,i+n) + "\n";
2835 // return ret + s.substring(i,s.length);
2837 // function byte2Hex(b) {
2839 // return "0" + b.toString(16);
2841 // return b.toString(16);
2843 function pkcs1pad1(s, n) {
2844 if (n < s.length + 22) {
2845 console.error("Message too long for RSA");
2848 var len = n - s.length - 6;
2850 for (var f = 0; f < len; f += 2) {
2853 var m = "0001" + filler + "00" + s;
2854 return parseBigInt(m, 16);
2856 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
2857 function pkcs1pad2(s, n) {
2858 if (n < s.length + 11) { // TODO: fix for utf-8
2859 console.error("Message too long for RSA");
2863 var i = s.length - 1;
2864 while (i >= 0 && n > 0) {
2865 var c = s.charCodeAt(i--);
2866 if (c < 128) { // encode using utf-8
2869 else if ((c > 127) && (c < 2048)) {
2870 ba[--n] = (c & 63) | 128;
2871 ba[--n] = (c >> 6) | 192;
2874 ba[--n] = (c & 63) | 128;
2875 ba[--n] = ((c >> 6) & 63) | 128;
2876 ba[--n] = (c >> 12) | 224;
2880 var rng = new SecureRandom();
2882 while (n > 2) { // random non-zero pad
2891 return new BigInteger(ba);
2893 // "empty" RSA key constructor
2894 var RSAKey = /** @class */ (function () {
2907 // RSAKey.prototype.doPublic = RSADoPublic;
2908 // Perform raw public operation on "x": return x^e (mod n)
2909 RSAKey.prototype.doPublic = function (x) {
2910 return x.modPowInt(this.e, this.n);
2912 // RSAKey.prototype.doPrivate = RSADoPrivate;
2913 // Perform raw private operation on "x": return x^d (mod n)
2914 RSAKey.prototype.doPrivate = function (x) {
2915 if (this.p == null || this.q == null) {
2916 return x.modPow(this.d, this.n);
2918 // TODO: re-calculate any missing CRT params
2919 var xp = x.mod(this.p).modPow(this.dmp1, this.p);
2920 var xq = x.mod(this.q).modPow(this.dmq1, this.q);
2921 while (xp.compareTo(xq) < 0) {
2922 xp = xp.add(this.p);
2924 return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
2926 //#endregion PROTECTED
2928 // RSAKey.prototype.setPublic = RSASetPublic;
2929 // Set the public key fields N and e from hex strings
2930 RSAKey.prototype.setPublic = function (N, E) {
2931 if (N != null && E != null && N.length > 0 && E.length > 0) {
2932 this.n = parseBigInt(N, 16);
2933 this.e = parseInt(E, 16);
2936 console.error("Invalid RSA public key");
2939 // RSAKey.prototype.encrypt = RSAEncrypt;
2940 // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
2941 RSAKey.prototype.encrypt = function (text) {
2942 var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
2946 var c = this.doPublic(m);
2950 var h = c.toString(16);
2951 if ((h.length & 1) == 0) {
2958 // RSAKey.prototype.setPrivate = RSASetPrivate;
2959 // Set the private key fields N, e, and d from hex strings
2960 RSAKey.prototype.setPrivate = function (N, E, D) {
2961 if (N != null && E != null && N.length > 0 && E.length > 0) {
2962 this.n = parseBigInt(N, 16);
2963 this.e = parseInt(E, 16);
2964 this.d = parseBigInt(D, 16);
2967 console.error("Invalid RSA private key");
2970 // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
2971 // Set the private key fields N, e, d and CRT params from hex strings
2972 RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
2973 if (N != null && E != null && N.length > 0 && E.length > 0) {
2974 this.n = parseBigInt(N, 16);
2975 this.e = parseInt(E, 16);
2976 this.d = parseBigInt(D, 16);
2977 this.p = parseBigInt(P, 16);
2978 this.q = parseBigInt(Q, 16);
2979 this.dmp1 = parseBigInt(DP, 16);
2980 this.dmq1 = parseBigInt(DQ, 16);
2981 this.coeff = parseBigInt(C, 16);
2984 console.error("Invalid RSA private key");
2987 // RSAKey.prototype.generate = RSAGenerate;
2988 // Generate a new random private key B bits long, using public expt E
2989 RSAKey.prototype.generate = function (B, E) {
2990 var rng = new SecureRandom();
2992 this.e = parseInt(E, 16);
2993 var ee = new BigInteger(E, 16);
2996 this.p = new BigInteger(B - qs, 1, rng);
2997 if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
3002 this.q = new BigInteger(qs, 1, rng);
3003 if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
3007 if (this.p.compareTo(this.q) <= 0) {
3012 var p1 = this.p.subtract(BigInteger.ONE);
3013 var q1 = this.q.subtract(BigInteger.ONE);
3014 var phi = p1.multiply(q1);
3015 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3016 this.n = this.p.multiply(this.q);
3017 this.d = ee.modInverse(phi);
3018 this.dmp1 = this.d.mod(p1);
3019 this.dmq1 = this.d.mod(q1);
3020 this.coeff = this.q.modInverse(this.p);
3025 // RSAKey.prototype.decrypt = RSADecrypt;
3026 // Return the PKCS#1 RSA decryption of "ctext".
3027 // "ctext" is an even-length hex string and the output is a plain string.
3028 RSAKey.prototype.decrypt = function (ctext) {
3029 var c = parseBigInt(ctext, 16);
3030 var m = this.doPrivate(c);
3034 return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
3036 // Generate a new random private key B bits long, using public expt E
3037 RSAKey.prototype.generateAsync = function (B, E, callback) {
3038 var rng = new SecureRandom();
3040 this.e = parseInt(E, 16);
3041 var ee = new BigInteger(E, 16);
3043 // These functions have non-descript names because they were originally for(;;) loops.
3044 // I don't know about cryptography to give them better names than loop1-4.
3045 var loop1 = function () {
3046 var loop4 = function () {
3047 if (rsa.p.compareTo(rsa.q) <= 0) {
3052 var p1 = rsa.p.subtract(BigInteger.ONE);
3053 var q1 = rsa.q.subtract(BigInteger.ONE);
3054 var phi = p1.multiply(q1);
3055 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3056 rsa.n = rsa.p.multiply(rsa.q);
3057 rsa.d = ee.modInverse(phi);
3058 rsa.dmp1 = rsa.d.mod(p1);
3059 rsa.dmq1 = rsa.d.mod(q1);
3060 rsa.coeff = rsa.q.modInverse(rsa.p);
3061 setTimeout(function () { callback(); }, 0); // escape
3064 setTimeout(loop1, 0);
3067 var loop3 = function () {
3069 rsa.q.fromNumberAsync(qs, 1, rng, function () {
3070 rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
3071 if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
3072 setTimeout(loop4, 0);
3075 setTimeout(loop3, 0);
3080 var loop2 = function () {
3082 rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
3083 rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
3084 if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
3085 setTimeout(loop3, 0);
3088 setTimeout(loop2, 0);
3093 setTimeout(loop2, 0);
3095 setTimeout(loop1, 0);
3097 RSAKey.prototype.sign = function (text, digestMethod, digestName) {
3098 var header = getDigestHeader(digestName);
3099 var digest = header + digestMethod(text).toString();
3100 var m = pkcs1pad1(digest, this.n.bitLength() / 4);
3104 var c = this.doPrivate(m);
3108 var h = c.toString(16);
3109 if ((h.length & 1) == 0) {
3116 RSAKey.prototype.verify = function (text, signature, digestMethod) {
3117 var c = parseBigInt(signature, 16);
3118 var m = this.doPublic(c);
3122 var unpadded = m.toString(16).replace(/^1f+00/, "");
3123 var digest = removeDigestHeader(unpadded);
3124 return digest == digestMethod(text).toString();
3128 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
3129 function pkcs1unpad2(d, n) {
3130 var b = d.toByteArray();
3132 while (i < b.length && b[i] == 0) {
3135 if (b.length - i != n - 1 || b[i] != 2) {
3140 if (++i >= b.length) {
3145 while (++i < b.length) {
3147 if (c < 128) { // utf-8 decode
3148 ret += String.fromCharCode(c);
3150 else if ((c > 191) && (c < 224)) {
3151 ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
3155 ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
3161 // https://tools.ietf.org/html/rfc3447#page-43
3162 var DIGEST_HEADERS = {
3163 md2: "3020300c06082a864886f70d020205000410",
3164 md5: "3020300c06082a864886f70d020505000410",
3165 sha1: "3021300906052b0e03021a05000414",
3166 sha224: "302d300d06096086480165030402040500041c",
3167 sha256: "3031300d060960864801650304020105000420",
3168 sha384: "3041300d060960864801650304020205000430",
3169 sha512: "3051300d060960864801650304020305000440",
3170 ripemd160: "3021300906052b2403020105000414",
3172 function getDigestHeader(name) {
3173 return DIGEST_HEADERS[name] || "";
3175 function removeDigestHeader(str) {
3176 for (var name_1 in DIGEST_HEADERS) {
3177 if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
3178 var header = DIGEST_HEADERS[name_1];
3179 var len = header.length;
3180 if (str.substr(0, len) == header) {
3181 return str.substr(len);
3187 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
3188 // function RSAEncryptB64(text) {
3189 // var h = this.encrypt(text);
3190 // if(h) return hex2b64(h); else return null;
3193 // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
3196 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3197 Code licensed under the BSD License:
3198 http://developer.yahoo.com/yui/license.html
3204 * Utility to set up the prototype, constructor and superclass properties to
3205 * support an inheritance strategy that can chain constructors and methods.
3206 * Static members will not be inherited.
3210 * @param {Function} subc the object to modify
3211 * @param {Function} superc the object to inherit
3212 * @param {Object} overrides additional properties/methods to add to the
3213 * subclass prototype. These will override the
3214 * matching items obtained from the superclass
3217 extend: function(subc, superc, overrides) {
3218 if (! superc || ! subc) {
3219 throw new Error("YAHOO.lang.extend failed, please check that " +
3220 "all dependencies are included.");
3223 var F = function() {};
3224 F.prototype = superc.prototype;
3225 subc.prototype = new F();
3226 subc.prototype.constructor = subc;
3227 subc.superclass = superc.prototype;
3229 if (superc.prototype.constructor == Object.prototype.constructor) {
3230 superc.prototype.constructor = superc;
3235 for (i in overrides) {
3236 subc.prototype[i] = overrides[i];
3240 * IE will not enumerate native functions in a derived object even if the
3241 * function was overridden. This is a workaround for specific functions
3242 * we care about on the Object prototype.
3243 * @property _IEEnumFix
3244 * @param {Function} r the object to receive the augmentation
3245 * @param {Function} s the object that supplies the properties to augment
3249 var _IEEnumFix = function() {},
3250 ADD = ["toString", "valueOf"];
3252 if (/MSIE/.test(navigator.userAgent)) {
3253 _IEEnumFix = function(r, s) {
3254 for (i = 0; i < ADD.length; i = i + 1) {
3255 var fname = ADD[i], f = s[fname];
3256 if (typeof f === 'function' && f != Object.prototype[fname]) {
3262 } catch (ex) {} _IEEnumFix(subc.prototype, overrides);
3267 /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
3273 * @author Kenji Urushima kenji.urushima@gmail.com
3274 * @version asn1 1.0.13 (2017-Jun-02)
3275 * @since jsrsasign 2.1
3276 * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
3280 * kjur's class library name space
3282 * This name space provides following name spaces:
3284 * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
3285 * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
3286 * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
3287 * class and utilities</li>
3290 * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
3292 * @namespace kjur's class library name space
3297 * kjur's ASN.1 class library name space
3299 * This is ITU-T X.690 ASN.1 DER encoder class library and
3300 * class structure and methods is very similar to
3301 * org.bouncycastle.asn1 package of
3302 * well known BouncyCaslte Cryptography Library.
3303 * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
3304 * Here are ASN.1 DER primitive classes.
3306 * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
3307 * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
3308 * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
3309 * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
3310 * <li>0x05 {@link KJUR.asn1.DERNull}</li>
3311 * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
3312 * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
3313 * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
3314 * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
3315 * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
3316 * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
3317 * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
3318 * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
3319 * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
3320 * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
3321 * <li>0x31 {@link KJUR.asn1.DERSet}</li>
3323 * <h4>OTHER ASN.1 CLASSES</h4>
3325 * <li>{@link KJUR.asn1.ASN1Object}</li>
3326 * <li>{@link KJUR.asn1.DERAbstractString}</li>
3327 * <li>{@link KJUR.asn1.DERAbstractTime}</li>
3328 * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
3329 * <li>{@link KJUR.asn1.DERTaggedObject}</li>
3331 * <h4>SUB NAME SPACES</h4>
3333 * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
3334 * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
3335 * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
3336 * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
3337 * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
3340 * NOTE: Please ignore method summary and document of this namespace.
3341 * This caused by a bug of jsdoc2.
3345 if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
3348 * ASN1 utilities class
3349 * @name KJUR.asn1.ASN1Util
3350 * @class ASN1 utilities class
3353 KJUR.asn1.ASN1Util = new function() {
3354 this.integerToByteHex = function(i) {
3355 var h = i.toString(16);
3356 if ((h.length % 2) == 1) h = '0' + h;
3359 this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
3360 var h = bigIntegerValue.toString(16);
3361 if (h.substr(0, 1) != '-') {
3362 if (h.length % 2 == 1) {
3365 if (! h.match(/^[0-7]/)) {
3370 var hPos = h.substr(1);
3371 var xorLen = hPos.length;
3372 if (xorLen % 2 == 1) {
3375 if (! h.match(/^[0-7]/)) {
3380 for (var i = 0; i < xorLen; i++) {
3383 var biMask = new BigInteger(hMask, 16);
3384 var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
3385 h = biNeg.toString(16).replace(/^-/, '');
3390 * get PEM string from hexadecimal data and header string
3391 * @name getPEMStringFromHex
3392 * @memberOf KJUR.asn1.ASN1Util
3394 * @param {String} dataHex hexadecimal string of PEM body
3395 * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
3396 * @return {String} PEM formatted string of input data
3398 * This method converts a hexadecimal string to a PEM string with
3399 * a specified header. Its line break will be CRLF("\r\n").
3401 * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
3402 * // value of pem will be:
3403 * -----BEGIN PRIVATE KEY-----
3405 * -----END PRIVATE KEY-----
3407 this.getPEMStringFromHex = function(dataHex, pemHeader) {
3408 return hextopem(dataHex, pemHeader);
3412 * generate ASN1Object specifed by JSON parameters
3414 * @memberOf KJUR.asn1.ASN1Util
3416 * @param {Array} param JSON parameter to generate ASN1Object
3417 * @return {KJUR.asn1.ASN1Object} generated object
3420 * generate any ASN1Object specified by JSON param
3421 * including ASN.1 primitive or structured.
3422 * Generally 'param' can be described as follows:
3424 * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
3426 * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
3428 * <li>'bool' - DERBoolean</li>
3429 * <li>'int' - DERInteger</li>
3430 * <li>'bitstr' - DERBitString</li>
3431 * <li>'octstr' - DEROctetString</li>
3432 * <li>'null' - DERNull</li>
3433 * <li>'oid' - DERObjectIdentifier</li>
3434 * <li>'enum' - DEREnumerated</li>
3435 * <li>'utf8str' - DERUTF8String</li>
3436 * <li>'numstr' - DERNumericString</li>
3437 * <li>'prnstr' - DERPrintableString</li>
3438 * <li>'telstr' - DERTeletexString</li>
3439 * <li>'ia5str' - DERIA5String</li>
3440 * <li>'utctime' - DERUTCTime</li>
3441 * <li>'gentime' - DERGeneralizedTime</li>
3442 * <li>'seq' - DERSequence</li>
3443 * <li>'set' - DERSet</li>
3444 * <li>'tag' - DERTaggedObject</li>
3447 * newObject({'prnstr': 'aaa'});
3448 * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
3449 * // ASN.1 Tagged Object
3450 * newObject({'tag': {'tag': 'a1',
3452 * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
3453 * // more simple representation of ASN.1 Tagged Object
3454 * newObject({'tag': ['a1',
3458 * {'prnstr': 'aaa'}]}
3461 this.newObject = function(param) {
3463 _KJUR_asn1 = _KJUR.asn1,
3464 _DERBoolean = _KJUR_asn1.DERBoolean,
3465 _DERInteger = _KJUR_asn1.DERInteger,
3466 _DERBitString = _KJUR_asn1.DERBitString,
3467 _DEROctetString = _KJUR_asn1.DEROctetString,
3468 _DERNull = _KJUR_asn1.DERNull,
3469 _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
3470 _DEREnumerated = _KJUR_asn1.DEREnumerated,
3471 _DERUTF8String = _KJUR_asn1.DERUTF8String,
3472 _DERNumericString = _KJUR_asn1.DERNumericString,
3473 _DERPrintableString = _KJUR_asn1.DERPrintableString,
3474 _DERTeletexString = _KJUR_asn1.DERTeletexString,
3475 _DERIA5String = _KJUR_asn1.DERIA5String,
3476 _DERUTCTime = _KJUR_asn1.DERUTCTime,
3477 _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
3478 _DERSequence = _KJUR_asn1.DERSequence,
3479 _DERSet = _KJUR_asn1.DERSet,
3480 _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
3481 _newObject = _KJUR_asn1.ASN1Util.newObject;
3483 var keys = Object.keys(param);
3484 if (keys.length != 1)
3485 throw "key of param shall be only one.";
3488 if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
3489 throw "undefined key: " + key;
3491 if (key == "bool") return new _DERBoolean(param[key]);
3492 if (key == "int") return new _DERInteger(param[key]);
3493 if (key == "bitstr") return new _DERBitString(param[key]);
3494 if (key == "octstr") return new _DEROctetString(param[key]);
3495 if (key == "null") return new _DERNull(param[key]);
3496 if (key == "oid") return new _DERObjectIdentifier(param[key]);
3497 if (key == "enum") return new _DEREnumerated(param[key]);
3498 if (key == "utf8str") return new _DERUTF8String(param[key]);
3499 if (key == "numstr") return new _DERNumericString(param[key]);
3500 if (key == "prnstr") return new _DERPrintableString(param[key]);
3501 if (key == "telstr") return new _DERTeletexString(param[key]);
3502 if (key == "ia5str") return new _DERIA5String(param[key]);
3503 if (key == "utctime") return new _DERUTCTime(param[key]);
3504 if (key == "gentime") return new _DERGeneralizedTime(param[key]);
3507 var paramList = param[key];
3509 for (var i = 0; i < paramList.length; i++) {
3510 var asn1Obj = _newObject(paramList[i]);
3513 return new _DERSequence({'array': a});
3517 var paramList = param[key];
3519 for (var i = 0; i < paramList.length; i++) {
3520 var asn1Obj = _newObject(paramList[i]);
3523 return new _DERSet({'array': a});
3527 var tagParam = param[key];
3528 if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
3529 tagParam.length == 3) {
3530 var obj = _newObject(tagParam[2]);
3531 return new _DERTaggedObject({tag: tagParam[0],
3532 explicit: tagParam[1],
3536 if (tagParam.explicit !== undefined)
3537 newParam.explicit = tagParam.explicit;
3538 if (tagParam.tag !== undefined)
3539 newParam.tag = tagParam.tag;
3540 if (tagParam.obj === undefined)
3541 throw "obj shall be specified for 'tag'.";
3542 newParam.obj = _newObject(tagParam.obj);
3543 return new _DERTaggedObject(newParam);
3549 * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
3550 * @name jsonToASN1HEX
3551 * @memberOf KJUR.asn1.ASN1Util
3553 * @param {Array} param JSON parameter to generate ASN1Object
3554 * @return hexadecimal string of ASN1Object
3557 * As for ASN.1 object representation of JSON object,
3558 * please see {@link newObject}.
3560 * jsonToASN1HEX({'prnstr': 'aaa'});
3562 this.jsonToASN1HEX = function(param) {
3563 var asn1Obj = this.newObject(param);
3564 return asn1Obj.getEncodedHex();
3569 * get dot noted oid number string from hexadecimal value of OID
3571 * @memberOf KJUR.asn1.ASN1Util
3573 * @param {String} hex hexadecimal value of object identifier
3574 * @return {String} dot noted string of object identifier
3575 * @since jsrsasign 4.8.3 asn1 1.0.7
3577 * This static method converts from hexadecimal string representation of
3578 * ASN.1 value of object identifier to oid number string.
3580 * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6"
3582 KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
3584 var i01 = parseInt(hex.substr(0, 2), 16);
3585 var i0 = Math.floor(i01 / 40);
3587 var s = i0 + "." + i1;
3590 for (var i = 2; i < hex.length; i += 2) {
3591 var value = parseInt(hex.substr(i, 2), 16);
3592 var bin = ("00000000" + value.toString(2)).slice(- 8);
3593 binbuf = binbuf + bin.substr(1, 7);
3594 if (bin.substr(0, 1) == "0") {
3595 var bi = new BigInteger(binbuf, 2);
3596 s = s + "." + bi.toString(10);
3604 * get hexadecimal value of object identifier from dot noted oid value
3606 * @memberOf KJUR.asn1.ASN1Util
3608 * @param {String} oidString dot noted string of object identifier
3609 * @return {String} hexadecimal value of object identifier
3610 * @since jsrsasign 4.8.3 asn1 1.0.7
3612 * This static method converts from object identifier value string.
3613 * to hexadecimal string representation of it.
3615 * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406"
3617 KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
3618 var itox = function(i) {
3619 var h = i.toString(16);
3620 if (h.length == 1) h = '0' + h;
3624 var roidtox = function(roid) {
3626 var bi = new BigInteger(roid, 10);
3627 var b = bi.toString(2);
3628 var padLen = 7 - b.length % 7;
3629 if (padLen == 7) padLen = 0;
3631 for (var i = 0; i < padLen; i++) bPad += '0';
3633 for (var i = 0; i < b.length - 1; i += 7) {
3634 var b8 = b.substr(i, 7);
3635 if (i != b.length - 7) b8 = '1' + b8;
3636 h += itox(parseInt(b8, 2));
3641 if (! oidString.match(/^[0-9.]+$/)) {
3642 throw "malformed oid string: " + oidString;
3645 var a = oidString.split('.');
3646 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
3649 for (var i = 0; i < a.length; i++) {
3656 // ********************************************************************
3657 // Abstract ASN.1 Classes
3658 // ********************************************************************
3660 // ********************************************************************
3663 * base class for ASN.1 DER encoder object
3664 * @name KJUR.asn1.ASN1Object
3665 * @class base class for ASN.1 DER encoder object
3666 * @property {Boolean} isModified flag whether internal data was changed
3667 * @property {String} hTLV hexadecimal string of ASN.1 TLV
3668 * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
3669 * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
3670 * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
3673 KJUR.asn1.ASN1Object = function() {
3677 * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
3678 * @name getLengthHexFromValue
3679 * @memberOf KJUR.asn1.ASN1Object#
3681 * @return {String} hexadecimal string of ASN.1 TLV length(L)
3683 this.getLengthHexFromValue = function() {
3684 if (typeof this.hV == "undefined" || this.hV == null) {
3685 throw "this.hV is null or undefined.";
3687 if (this.hV.length % 2 == 1) {
3688 throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
3690 var n = this.hV.length / 2;
3691 var hN = n.toString(16);
3692 if (hN.length % 2 == 1) {
3698 var hNlen = hN.length / 2;
3700 throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
3702 var head = 128 + hNlen;
3703 return head.toString(16) + hN;
3708 * get hexadecimal string of ASN.1 TLV bytes
3709 * @name getEncodedHex
3710 * @memberOf KJUR.asn1.ASN1Object#
3712 * @return {String} hexadecimal string of ASN.1 TLV
3714 this.getEncodedHex = function() {
3715 if (this.hTLV == null || this.isModified) {
3716 this.hV = this.getFreshValueHex();
3717 this.hL = this.getLengthHexFromValue();
3718 this.hTLV = this.hT + this.hL + this.hV;
3719 this.isModified = false;
3720 //alert("first time: " + this.hTLV);
3726 * get hexadecimal string of ASN.1 TLV value(V) bytes
3728 * @memberOf KJUR.asn1.ASN1Object#
3730 * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
3732 this.getValueHex = function() {
3733 this.getEncodedHex();
3737 this.getFreshValueHex = function() {
3742 // == BEGIN DERAbstractString ================================================
3744 * base class for ASN.1 DER string classes
3745 * @name KJUR.asn1.DERAbstractString
3746 * @class base class for ASN.1 DER string classes
3747 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
3748 * @property {String} s internal string of value
3749 * @extends KJUR.asn1.ASN1Object
3752 * As for argument 'params' for constructor, you can specify one of
3753 * following properties:
3755 * <li>str - specify initial ASN.1 value(V) by a string</li>
3756 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
3758 * NOTE: 'params' can be omitted.
3760 KJUR.asn1.DERAbstractString = function(params) {
3761 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3764 * get string value of this string object
3766 * @memberOf KJUR.asn1.DERAbstractString#
3768 * @return {String} string value of this string object
3770 this.getString = function() {
3775 * set value by a string
3777 * @memberOf KJUR.asn1.DERAbstractString#
3779 * @param {String} newS value by a string to set
3781 this.setString = function(newS) {
3783 this.isModified = true;
3785 this.hV = stohex(this.s);
3789 * set value by a hexadecimal string
3790 * @name setStringHex
3791 * @memberOf KJUR.asn1.DERAbstractString#
3793 * @param {String} newHexString value by a hexadecimal string to set
3795 this.setStringHex = function(newHexString) {
3797 this.isModified = true;
3799 this.hV = newHexString;
3802 this.getFreshValueHex = function() {
3806 if (typeof params != "undefined") {
3807 if (typeof params == "string") {
3808 this.setString(params);
3809 } else if (typeof params['str'] != "undefined") {
3810 this.setString(params['str']);
3811 } else if (typeof params['hex'] != "undefined") {
3812 this.setStringHex(params['hex']);
3816 YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
3817 // == END DERAbstractString ================================================
3819 // == BEGIN DERAbstractTime ==================================================
3821 * base class for ASN.1 DER Generalized/UTCTime class
3822 * @name KJUR.asn1.DERAbstractTime
3823 * @class base class for ASN.1 DER Generalized/UTCTime class
3824 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
3825 * @extends KJUR.asn1.ASN1Object
3827 * @see KJUR.asn1.ASN1Object - superclass
3829 KJUR.asn1.DERAbstractTime = function(params) {
3830 KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
3832 // --- PRIVATE METHODS --------------------
3833 this.localDateToUTC = function(d) {
3834 utc = d.getTime() + (d.getTimezoneOffset() * 60000);
3835 var utcDate = new Date(utc);
3840 * format date string by Data object
3842 * @memberOf KJUR.asn1.AbstractTime;
3843 * @param {Date} dateObject
3844 * @param {string} type 'utc' or 'gen'
3845 * @param {boolean} withMillis flag for with millisections or not
3847 * 'withMillis' flag is supported from asn1 1.0.6.
3849 this.formatDate = function(dateObject, type, withMillis) {
3850 var pad = this.zeroPadding;
3851 var d = this.localDateToUTC(dateObject);
3852 var year = String(d.getFullYear());
3853 if (type == 'utc') year = year.substr(2, 2);
3854 var month = pad(String(d.getMonth() + 1), 2);
3855 var day = pad(String(d.getDate()), 2);
3856 var hour = pad(String(d.getHours()), 2);
3857 var min = pad(String(d.getMinutes()), 2);
3858 var sec = pad(String(d.getSeconds()), 2);
3859 var s = year + month + day + hour + min + sec;
3860 if (withMillis === true) {
3861 var millis = d.getMilliseconds();
3863 var sMillis = pad(String(millis), 3);
3864 sMillis = sMillis.replace(/[0]+$/, "");
3865 s = s + "." + sMillis;
3871 this.zeroPadding = function(s, len) {
3872 if (s.length >= len) return s;
3873 return new Array(len - s.length + 1).join('0') + s;
3876 // --- PUBLIC METHODS --------------------
3878 * get string value of this string object
3880 * @memberOf KJUR.asn1.DERAbstractTime#
3882 * @return {String} string value of this time object
3884 this.getString = function() {
3889 * set value by a string
3891 * @memberOf KJUR.asn1.DERAbstractTime#
3893 * @param {String} newS value by a string to set such like "130430235959Z"
3895 this.setString = function(newS) {
3897 this.isModified = true;
3899 this.hV = stohex(newS);
3903 * set value by a Date object
3904 * @name setByDateValue
3905 * @memberOf KJUR.asn1.DERAbstractTime#
3907 * @param {Integer} year year of date (ex. 2013)
3908 * @param {Integer} month month of date between 1 and 12 (ex. 12)
3909 * @param {Integer} day day of month
3910 * @param {Integer} hour hours of date
3911 * @param {Integer} min minutes of date
3912 * @param {Integer} sec seconds of date
3914 this.setByDateValue = function(year, month, day, hour, min, sec) {
3915 var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
3916 this.setByDate(dateObject);
3919 this.getFreshValueHex = function() {
3923 YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
3924 // == END DERAbstractTime ==================================================
3926 // == BEGIN DERAbstractStructured ============================================
3928 * base class for ASN.1 DER structured class
3929 * @name KJUR.asn1.DERAbstractStructured
3930 * @class base class for ASN.1 DER structured class
3931 * @property {Array} asn1Array internal array of ASN1Object
3932 * @extends KJUR.asn1.ASN1Object
3934 * @see KJUR.asn1.ASN1Object - superclass
3936 KJUR.asn1.DERAbstractStructured = function(params) {
3937 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3940 * set value by array of ASN1Object
3941 * @name setByASN1ObjectArray
3942 * @memberOf KJUR.asn1.DERAbstractStructured#
3944 * @param {array} asn1ObjectArray array of ASN1Object to set
3946 this.setByASN1ObjectArray = function(asn1ObjectArray) {
3948 this.isModified = true;
3949 this.asn1Array = asn1ObjectArray;
3953 * append an ASN1Object to internal array
3954 * @name appendASN1Object
3955 * @memberOf KJUR.asn1.DERAbstractStructured#
3957 * @param {ASN1Object} asn1Object to add
3959 this.appendASN1Object = function(asn1Object) {
3961 this.isModified = true;
3962 this.asn1Array.push(asn1Object);
3965 this.asn1Array = new Array();
3966 if (typeof params != "undefined") {
3967 if (typeof params['array'] != "undefined") {
3968 this.asn1Array = params['array'];
3972 YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
3975 // ********************************************************************
3976 // ASN.1 Object Classes
3977 // ********************************************************************
3979 // ********************************************************************
3981 * class for ASN.1 DER Boolean
3982 * @name KJUR.asn1.DERBoolean
3983 * @class class for ASN.1 DER Boolean
3984 * @extends KJUR.asn1.ASN1Object
3986 * @see KJUR.asn1.ASN1Object - superclass
3988 KJUR.asn1.DERBoolean = function() {
3989 KJUR.asn1.DERBoolean.superclass.constructor.call(this);
3991 this.hTLV = "0101ff";
3993 YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
3995 // ********************************************************************
3997 * class for ASN.1 DER Integer
3998 * @name KJUR.asn1.DERInteger
3999 * @class class for ASN.1 DER Integer
4000 * @extends KJUR.asn1.ASN1Object
4003 * As for argument 'params' for constructor, you can specify one of
4004 * following properties:
4006 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4007 * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
4008 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4010 * NOTE: 'params' can be omitted.
4012 KJUR.asn1.DERInteger = function(params) {
4013 KJUR.asn1.DERInteger.superclass.constructor.call(this);
4017 * set value by Tom Wu's BigInteger object
4018 * @name setByBigInteger
4019 * @memberOf KJUR.asn1.DERInteger#
4021 * @param {BigInteger} bigIntegerValue to set
4023 this.setByBigInteger = function(bigIntegerValue) {
4025 this.isModified = true;
4026 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4030 * set value by integer value
4031 * @name setByInteger
4032 * @memberOf KJUR.asn1.DERInteger
4034 * @param {Integer} integer value to set
4036 this.setByInteger = function(intValue) {
4037 var bi = new BigInteger(String(intValue), 10);
4038 this.setByBigInteger(bi);
4042 * set value by integer value
4044 * @memberOf KJUR.asn1.DERInteger#
4046 * @param {String} hexadecimal string of integer value
4049 * NOTE: Value shall be represented by minimum octet length of
4050 * two's complement representation.
4052 * new KJUR.asn1.DERInteger(123);
4053 * new KJUR.asn1.DERInteger({'int': 123});
4054 * new KJUR.asn1.DERInteger({'hex': '1fad'});
4056 this.setValueHex = function(newHexString) {
4057 this.hV = newHexString;
4060 this.getFreshValueHex = function() {
4064 if (typeof params != "undefined") {
4065 if (typeof params['bigint'] != "undefined") {
4066 this.setByBigInteger(params['bigint']);
4067 } else if (typeof params['int'] != "undefined") {
4068 this.setByInteger(params['int']);
4069 } else if (typeof params == "number") {
4070 this.setByInteger(params);
4071 } else if (typeof params['hex'] != "undefined") {
4072 this.setValueHex(params['hex']);
4076 YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
4078 // ********************************************************************
4080 * class for ASN.1 DER encoded BitString primitive
4081 * @name KJUR.asn1.DERBitString
4082 * @class class for ASN.1 DER encoded BitString primitive
4083 * @extends KJUR.asn1.ASN1Object
4086 * As for argument 'params' for constructor, you can specify one of
4087 * following properties:
4089 * <li>bin - specify binary string (ex. '10111')</li>
4090 * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
4091 * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
4092 * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
4093 * argument for "BitString encapsulates" structure.</li>
4095 * NOTE1: 'params' can be omitted.<br/>
4096 * NOTE2: 'obj' parameter have been supported since
4097 * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
4099 * // default constructor
4100 * o = new KJUR.asn1.DERBitString();
4101 * // initialize with binary string
4102 * o = new KJUR.asn1.DERBitString({bin: "1011"});
4103 * // initialize with boolean array
4104 * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
4105 * // initialize with hexadecimal string (04 is unused bits)
4106 * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
4107 * // initialize with ASN1Util.newObject argument for encapsulated
4108 * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4109 * // above generates a ASN.1 data like this:
4110 * // BIT STRING, encapsulates {
4113 * // PrintableString 'aaa'
4117 KJUR.asn1.DERBitString = function(params) {
4118 if (params !== undefined && typeof params.obj !== "undefined") {
4119 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4120 params.hex = "00" + o.getEncodedHex();
4122 KJUR.asn1.DERBitString.superclass.constructor.call(this);
4126 * set ASN.1 value(V) by a hexadecimal string including unused bits
4127 * @name setHexValueIncludingUnusedBits
4128 * @memberOf KJUR.asn1.DERBitString#
4130 * @param {String} newHexStringIncludingUnusedBits
4132 this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
4134 this.isModified = true;
4135 this.hV = newHexStringIncludingUnusedBits;
4139 * set ASN.1 value(V) by unused bit and hexadecimal string of value
4140 * @name setUnusedBitsAndHexValue
4141 * @memberOf KJUR.asn1.DERBitString#
4143 * @param {Integer} unusedBits
4144 * @param {String} hValue
4146 this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
4147 if (unusedBits < 0 || 7 < unusedBits) {
4148 throw "unused bits shall be from 0 to 7: u = " + unusedBits;
4150 var hUnusedBits = "0" + unusedBits;
4152 this.isModified = true;
4153 this.hV = hUnusedBits + hValue;
4157 * set ASN.1 DER BitString by binary string<br/>
4158 * @name setByBinaryString
4159 * @memberOf KJUR.asn1.DERBitString#
4161 * @param {String} binaryString binary value string (i.e. '10111')
4163 * Its unused bits will be calculated automatically by length of
4164 * 'binaryValue'. <br/>
4165 * NOTE: Trailing zeros '0' will be ignored.
4167 * o = new KJUR.asn1.DERBitString();
4168 * o.setByBooleanArray("01011");
4170 this.setByBinaryString = function(binaryString) {
4171 binaryString = binaryString.replace(/0+$/, '');
4172 var unusedBits = 8 - binaryString.length % 8;
4173 if (unusedBits == 8) unusedBits = 0;
4174 for (var i = 0; i <= unusedBits; i++) {
4175 binaryString += '0';
4178 for (var i = 0; i < binaryString.length - 1; i += 8) {
4179 var b = binaryString.substr(i, 8);
4180 var x = parseInt(b, 2).toString(16);
4181 if (x.length == 1) x = '0' + x;
4185 this.isModified = true;
4186 this.hV = '0' + unusedBits + h;
4190 * set ASN.1 TLV value(V) by an array of boolean<br/>
4191 * @name setByBooleanArray
4192 * @memberOf KJUR.asn1.DERBitString#
4194 * @param {array} booleanArray array of boolean (ex. [true, false, true])
4196 * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
4198 * o = new KJUR.asn1.DERBitString();
4199 * o.setByBooleanArray([false, true, false, true, true]);
4201 this.setByBooleanArray = function(booleanArray) {
4203 for (var i = 0; i < booleanArray.length; i++) {
4204 if (booleanArray[i] == true) {
4210 this.setByBinaryString(s);
4214 * generate an array of falses with specified length<br/>
4215 * @name newFalseArray
4216 * @memberOf KJUR.asn1.DERBitString
4218 * @param {Integer} nLength length of array to generate
4219 * @return {array} array of boolean falses
4221 * This static method may be useful to initialize boolean array.
4223 * o = new KJUR.asn1.DERBitString();
4224 * o.newFalseArray(3) → [false, false, false]
4226 this.newFalseArray = function(nLength) {
4227 var a = new Array(nLength);
4228 for (var i = 0; i < nLength; i++) {
4234 this.getFreshValueHex = function() {
4238 if (typeof params != "undefined") {
4239 if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
4240 this.setHexValueIncludingUnusedBits(params);
4241 } else if (typeof params['hex'] != "undefined") {
4242 this.setHexValueIncludingUnusedBits(params['hex']);
4243 } else if (typeof params['bin'] != "undefined") {
4244 this.setByBinaryString(params['bin']);
4245 } else if (typeof params['array'] != "undefined") {
4246 this.setByBooleanArray(params['array']);
4250 YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
4252 // ********************************************************************
4254 * class for ASN.1 DER OctetString<br/>
4255 * @name KJUR.asn1.DEROctetString
4256 * @class class for ASN.1 DER OctetString
4257 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4258 * @extends KJUR.asn1.DERAbstractString
4260 * This class provides ASN.1 OctetString simple type.<br/>
4261 * Supported "params" attributes are:
4263 * <li>str - to set a string as a value</li>
4264 * <li>hex - to set a hexadecimal string as a value</li>
4265 * <li>obj - to set a encapsulated ASN.1 value by JSON object
4266 * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
4268 * NOTE: A parameter 'obj' have been supported
4269 * for "OCTET STRING, encapsulates" structure.
4270 * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
4271 * @see KJUR.asn1.DERAbstractString - superclass
4273 * // default constructor
4274 * o = new KJUR.asn1.DEROctetString();
4275 * // initialize with string
4276 * o = new KJUR.asn1.DEROctetString({str: "aaa"});
4277 * // initialize with hexadecimal string
4278 * o = new KJUR.asn1.DEROctetString({hex: "616161"});
4279 * // initialize with ASN1Util.newObject argument
4280 * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4281 * // above generates a ASN.1 data like this:
4282 * // OCTET STRING, encapsulates {
4285 * // PrintableString 'aaa'
4289 KJUR.asn1.DEROctetString = function(params) {
4290 if (params !== undefined && typeof params.obj !== "undefined") {
4291 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4292 params.hex = o.getEncodedHex();
4294 KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
4297 YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
4299 // ********************************************************************
4301 * class for ASN.1 DER Null
4302 * @name KJUR.asn1.DERNull
4303 * @class class for ASN.1 DER Null
4304 * @extends KJUR.asn1.ASN1Object
4306 * @see KJUR.asn1.ASN1Object - superclass
4308 KJUR.asn1.DERNull = function() {
4309 KJUR.asn1.DERNull.superclass.constructor.call(this);
4313 YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
4315 // ********************************************************************
4317 * class for ASN.1 DER ObjectIdentifier
4318 * @name KJUR.asn1.DERObjectIdentifier
4319 * @class class for ASN.1 DER ObjectIdentifier
4320 * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
4321 * @extends KJUR.asn1.ASN1Object
4324 * As for argument 'params' for constructor, you can specify one of
4325 * following properties:
4327 * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
4328 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4330 * NOTE: 'params' can be omitted.
4332 KJUR.asn1.DERObjectIdentifier = function(params) {
4333 var itox = function(i) {
4334 var h = i.toString(16);
4335 if (h.length == 1) h = '0' + h;
4338 var roidtox = function(roid) {
4340 var bi = new BigInteger(roid, 10);
4341 var b = bi.toString(2);
4342 var padLen = 7 - b.length % 7;
4343 if (padLen == 7) padLen = 0;
4345 for (var i = 0; i < padLen; i++) bPad += '0';
4347 for (var i = 0; i < b.length - 1; i += 7) {
4348 var b8 = b.substr(i, 7);
4349 if (i != b.length - 7) b8 = '1' + b8;
4350 h += itox(parseInt(b8, 2));
4355 KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
4359 * set value by a hexadecimal string
4361 * @memberOf KJUR.asn1.DERObjectIdentifier#
4363 * @param {String} newHexString hexadecimal value of OID bytes
4365 this.setValueHex = function(newHexString) {
4367 this.isModified = true;
4369 this.hV = newHexString;
4373 * set value by a OID string<br/>
4374 * @name setValueOidString
4375 * @memberOf KJUR.asn1.DERObjectIdentifier#
4377 * @param {String} oidString OID string (ex. 2.5.4.13)
4379 * o = new KJUR.asn1.DERObjectIdentifier();
4380 * o.setValueOidString("2.5.4.13");
4382 this.setValueOidString = function(oidString) {
4383 if (! oidString.match(/^[0-9.]+$/)) {
4384 throw "malformed oid string: " + oidString;
4387 var a = oidString.split('.');
4388 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
4391 for (var i = 0; i < a.length; i++) {
4395 this.isModified = true;
4401 * set value by a OID name
4402 * @name setValueName
4403 * @memberOf KJUR.asn1.DERObjectIdentifier#
4405 * @param {String} oidName OID name (ex. 'serverAuth')
4408 * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
4409 * Otherwise raise error.
4411 * o = new KJUR.asn1.DERObjectIdentifier();
4412 * o.setValueName("serverAuth");
4414 this.setValueName = function(oidName) {
4415 var oid = KJUR.asn1.x509.OID.name2oid(oidName);
4417 this.setValueOidString(oid);
4419 throw "DERObjectIdentifier oidName undefined: " + oidName;
4423 this.getFreshValueHex = function() {
4427 if (params !== undefined) {
4428 if (typeof params === "string") {
4429 if (params.match(/^[0-2].[0-9.]+$/)) {
4430 this.setValueOidString(params);
4432 this.setValueName(params);
4434 } else if (params.oid !== undefined) {
4435 this.setValueOidString(params.oid);
4436 } else if (params.hex !== undefined) {
4437 this.setValueHex(params.hex);
4438 } else if (params.name !== undefined) {
4439 this.setValueName(params.name);
4443 YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
4445 // ********************************************************************
4447 * class for ASN.1 DER Enumerated
4448 * @name KJUR.asn1.DEREnumerated
4449 * @class class for ASN.1 DER Enumerated
4450 * @extends KJUR.asn1.ASN1Object
4453 * As for argument 'params' for constructor, you can specify one of
4454 * following properties:
4456 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4457 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4459 * NOTE: 'params' can be omitted.
4461 * new KJUR.asn1.DEREnumerated(123);
4462 * new KJUR.asn1.DEREnumerated({int: 123});
4463 * new KJUR.asn1.DEREnumerated({hex: '1fad'});
4465 KJUR.asn1.DEREnumerated = function(params) {
4466 KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
4470 * set value by Tom Wu's BigInteger object
4471 * @name setByBigInteger
4472 * @memberOf KJUR.asn1.DEREnumerated#
4474 * @param {BigInteger} bigIntegerValue to set
4476 this.setByBigInteger = function(bigIntegerValue) {
4478 this.isModified = true;
4479 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4483 * set value by integer value
4484 * @name setByInteger
4485 * @memberOf KJUR.asn1.DEREnumerated#
4487 * @param {Integer} integer value to set
4489 this.setByInteger = function(intValue) {
4490 var bi = new BigInteger(String(intValue), 10);
4491 this.setByBigInteger(bi);
4495 * set value by integer value
4497 * @memberOf KJUR.asn1.DEREnumerated#
4499 * @param {String} hexadecimal string of integer value
4502 * NOTE: Value shall be represented by minimum octet length of
4503 * two's complement representation.
4505 this.setValueHex = function(newHexString) {
4506 this.hV = newHexString;
4509 this.getFreshValueHex = function() {
4513 if (typeof params != "undefined") {
4514 if (typeof params['int'] != "undefined") {
4515 this.setByInteger(params['int']);
4516 } else if (typeof params == "number") {
4517 this.setByInteger(params);
4518 } else if (typeof params['hex'] != "undefined") {
4519 this.setValueHex(params['hex']);
4523 YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
4525 // ********************************************************************
4527 * class for ASN.1 DER UTF8String
4528 * @name KJUR.asn1.DERUTF8String
4529 * @class class for ASN.1 DER UTF8String
4530 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4531 * @extends KJUR.asn1.DERAbstractString
4533 * @see KJUR.asn1.DERAbstractString - superclass
4535 KJUR.asn1.DERUTF8String = function(params) {
4536 KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
4539 YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
4541 // ********************************************************************
4543 * class for ASN.1 DER NumericString
4544 * @name KJUR.asn1.DERNumericString
4545 * @class class for ASN.1 DER NumericString
4546 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4547 * @extends KJUR.asn1.DERAbstractString
4549 * @see KJUR.asn1.DERAbstractString - superclass
4551 KJUR.asn1.DERNumericString = function(params) {
4552 KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
4555 YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
4557 // ********************************************************************
4559 * class for ASN.1 DER PrintableString
4560 * @name KJUR.asn1.DERPrintableString
4561 * @class class for ASN.1 DER PrintableString
4562 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4563 * @extends KJUR.asn1.DERAbstractString
4565 * @see KJUR.asn1.DERAbstractString - superclass
4567 KJUR.asn1.DERPrintableString = function(params) {
4568 KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
4571 YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
4573 // ********************************************************************
4575 * class for ASN.1 DER TeletexString
4576 * @name KJUR.asn1.DERTeletexString
4577 * @class class for ASN.1 DER TeletexString
4578 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4579 * @extends KJUR.asn1.DERAbstractString
4581 * @see KJUR.asn1.DERAbstractString - superclass
4583 KJUR.asn1.DERTeletexString = function(params) {
4584 KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
4587 YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
4589 // ********************************************************************
4591 * class for ASN.1 DER IA5String
4592 * @name KJUR.asn1.DERIA5String
4593 * @class class for ASN.1 DER IA5String
4594 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4595 * @extends KJUR.asn1.DERAbstractString
4597 * @see KJUR.asn1.DERAbstractString - superclass
4599 KJUR.asn1.DERIA5String = function(params) {
4600 KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
4603 YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
4605 // ********************************************************************
4607 * class for ASN.1 DER UTCTime
4608 * @name KJUR.asn1.DERUTCTime
4609 * @class class for ASN.1 DER UTCTime
4610 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
4611 * @extends KJUR.asn1.DERAbstractTime
4614 * As for argument 'params' for constructor, you can specify one of
4615 * following properties:
4617 * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
4618 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4619 * <li>date - specify Date object.</li>
4621 * NOTE: 'params' can be omitted.
4624 * d1 = new KJUR.asn1.DERUTCTime();
4625 * d1.setString('130430125959Z');
4627 * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
4628 * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
4629 * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
4631 KJUR.asn1.DERUTCTime = function(params) {
4632 KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
4636 * set value by a Date object<br/>
4638 * @memberOf KJUR.asn1.DERUTCTime#
4640 * @param {Date} dateObject Date object to set ASN.1 value(V)
4642 * o = new KJUR.asn1.DERUTCTime();
4643 * o.setByDate(new Date("2016/12/31"));
4645 this.setByDate = function(dateObject) {
4647 this.isModified = true;
4648 this.date = dateObject;
4649 this.s = this.formatDate(this.date, 'utc');
4650 this.hV = stohex(this.s);
4653 this.getFreshValueHex = function() {
4654 if (typeof this.date == "undefined" && typeof this.s == "undefined") {
4655 this.date = new Date();
4656 this.s = this.formatDate(this.date, 'utc');
4657 this.hV = stohex(this.s);
4662 if (params !== undefined) {
4663 if (params.str !== undefined) {
4664 this.setString(params.str);
4665 } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
4666 this.setString(params);
4667 } else if (params.hex !== undefined) {
4668 this.setStringHex(params.hex);
4669 } else if (params.date !== undefined) {
4670 this.setByDate(params.date);
4674 YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
4676 // ********************************************************************
4678 * class for ASN.1 DER GeneralizedTime
4679 * @name KJUR.asn1.DERGeneralizedTime
4680 * @class class for ASN.1 DER GeneralizedTime
4681 * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
4682 * @property {Boolean} withMillis flag to show milliseconds or not
4683 * @extends KJUR.asn1.DERAbstractTime
4686 * As for argument 'params' for constructor, you can specify one of
4687 * following properties:
4689 * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
4690 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4691 * <li>date - specify Date object.</li>
4692 * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
4694 * NOTE1: 'params' can be omitted.
4695 * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
4697 KJUR.asn1.DERGeneralizedTime = function(params) {
4698 KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
4700 this.withMillis = false;
4703 * set value by a Date object
4705 * @memberOf KJUR.asn1.DERGeneralizedTime#
4707 * @param {Date} dateObject Date object to set ASN.1 value(V)
4709 * When you specify UTC time, use 'Date.UTC' method like this:<br/>
4710 * o1 = new DERUTCTime();
4711 * o1.setByDate(date);
4713 * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
4715 this.setByDate = function(dateObject) {
4717 this.isModified = true;
4718 this.date = dateObject;
4719 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4720 this.hV = stohex(this.s);
4723 this.getFreshValueHex = function() {
4724 if (this.date === undefined && this.s === undefined) {
4725 this.date = new Date();
4726 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4727 this.hV = stohex(this.s);
4732 if (params !== undefined) {
4733 if (params.str !== undefined) {
4734 this.setString(params.str);
4735 } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
4736 this.setString(params);
4737 } else if (params.hex !== undefined) {
4738 this.setStringHex(params.hex);
4739 } else if (params.date !== undefined) {
4740 this.setByDate(params.date);
4742 if (params.millis === true) {
4743 this.withMillis = true;
4747 YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
4749 // ********************************************************************
4751 * class for ASN.1 DER Sequence
4752 * @name KJUR.asn1.DERSequence
4753 * @class class for ASN.1 DER Sequence
4754 * @extends KJUR.asn1.DERAbstractStructured
4757 * As for argument 'params' for constructor, you can specify one of
4758 * following properties:
4760 * <li>array - specify array of ASN1Object to set elements of content</li>
4762 * NOTE: 'params' can be omitted.
4764 KJUR.asn1.DERSequence = function(params) {
4765 KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
4767 this.getFreshValueHex = function() {
4769 for (var i = 0; i < this.asn1Array.length; i++) {
4770 var asn1Obj = this.asn1Array[i];
4771 h += asn1Obj.getEncodedHex();
4777 YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
4779 // ********************************************************************
4781 * class for ASN.1 DER Set
4782 * @name KJUR.asn1.DERSet
4783 * @class class for ASN.1 DER Set
4784 * @extends KJUR.asn1.DERAbstractStructured
4787 * As for argument 'params' for constructor, you can specify one of
4788 * following properties:
4790 * <li>array - specify array of ASN1Object to set elements of content</li>
4791 * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
4793 * NOTE1: 'params' can be omitted.<br/>
4794 * NOTE2: sortflag is supported since 1.0.5.
4796 KJUR.asn1.DERSet = function(params) {
4797 KJUR.asn1.DERSet.superclass.constructor.call(this, params);
4799 this.sortFlag = true; // item shall be sorted only in ASN.1 DER
4800 this.getFreshValueHex = function() {
4801 var a = new Array();
4802 for (var i = 0; i < this.asn1Array.length; i++) {
4803 var asn1Obj = this.asn1Array[i];
4804 a.push(asn1Obj.getEncodedHex());
4806 if (this.sortFlag == true) a.sort();
4807 this.hV = a.join('');
4811 if (typeof params != "undefined") {
4812 if (typeof params.sortflag != "undefined" &&
4813 params.sortflag == false)
4814 this.sortFlag = false;
4817 YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
4819 // ********************************************************************
4821 * class for ASN.1 DER TaggedObject
4822 * @name KJUR.asn1.DERTaggedObject
4823 * @class class for ASN.1 DER TaggedObject
4824 * @extends KJUR.asn1.ASN1Object
4827 * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
4828 * For example, if you find '[1]' tag in a ASN.1 dump,
4829 * 'tagNoHex' will be 'a1'.
4831 * As for optional argument 'params' for constructor, you can specify *ANY* of
4832 * following properties:
4834 * <li>explicit - specify true if this is explicit tag otherwise false
4835 * (default is 'true').</li>
4836 * <li>tag - specify tag (default is 'a0' which means [0])</li>
4837 * <li>obj - specify ASN1Object which is tagged</li>
4840 * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
4841 * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
4842 * hex = d2.getEncodedHex();
4844 KJUR.asn1.DERTaggedObject = function(params) {
4845 KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
4848 this.isExplicit = true;
4849 this.asn1Object = null;
4852 * set value by an ASN1Object
4854 * @memberOf KJUR.asn1.DERTaggedObject#
4856 * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
4857 * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
4858 * @param {ASN1Object} asn1Object ASN.1 to encapsulate
4860 this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
4862 this.isExplicit = isExplicitFlag;
4863 this.asn1Object = asn1Object;
4864 if (this.isExplicit) {
4865 this.hV = this.asn1Object.getEncodedHex();
4867 this.isModified = true;
4870 this.hTLV = asn1Object.getEncodedHex();
4871 this.hTLV = this.hTLV.replace(/^../, tagNoHex);
4872 this.isModified = false;
4876 this.getFreshValueHex = function() {
4880 if (typeof params != "undefined") {
4881 if (typeof params['tag'] != "undefined") {
4882 this.hT = params['tag'];
4884 if (typeof params['explicit'] != "undefined") {
4885 this.isExplicit = params['explicit'];
4887 if (typeof params['obj'] != "undefined") {
4888 this.asn1Object = params['obj'];
4889 this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
4893 YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
4896 * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
4897 * This object is just a decorator for parsing the key parameter
4898 * @param {string|Object} key - The key in string format, or an object containing
4899 * the parameters needed to build a RSAKey object.
4902 var JSEncryptRSAKey = /** @class */ (function (_super) {
4903 __extends(JSEncryptRSAKey, _super);
4904 function JSEncryptRSAKey(key) {
4905 var _this = _super.call(this) || this;
4906 // Call the super constructor.
4907 // RSAKey.call(this);
4908 // If a key key was provided.
4910 // If this is a string...
4911 if (typeof key === "string") {
4912 _this.parseKey(key);
4914 else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
4915 JSEncryptRSAKey.hasPublicKeyProperty(key)) {
4916 // Set the values for the key.
4917 _this.parsePropertiesFrom(key);
4923 * Method to parse a pem encoded string containing both a public or private key.
4924 * The method will translate the pem encoded string in a der encoded string and
4925 * will parse private key and public key parameters. This method accepts public key
4926 * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
4928 * @todo Check how many rsa formats use the same format of pkcs #1.
4930 * The format is defined as:
4931 * PublicKeyInfo ::= SEQUENCE {
4932 * algorithm AlgorithmIdentifier,
4933 * PublicKey BIT STRING
4935 * Where AlgorithmIdentifier is:
4936 * AlgorithmIdentifier ::= SEQUENCE {
4937 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
4938 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
4940 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
4941 * RSAPublicKey ::= SEQUENCE {
4942 * modulus INTEGER, -- n
4943 * publicExponent INTEGER -- e
4945 * it's possible to examine the structure of the keys obtained from openssl using
4946 * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
4947 * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
4950 JSEncryptRSAKey.prototype.parseKey = function (pem) {
4953 var public_exponent = 0;
4954 var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
4955 var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
4956 var asn1 = ASN1.decode(der);
4957 // Fixes a bug with OpenSSL 1.0+ private keys
4958 if (asn1.sub.length === 3) {
4959 asn1 = asn1.sub[2].sub[0];
4961 if (asn1.sub.length === 9) {
4962 // Parse the private key.
4963 modulus = asn1.sub[1].getHexStringValue(); // bigint
4964 this.n = parseBigInt(modulus, 16);
4965 public_exponent = asn1.sub[2].getHexStringValue(); // int
4966 this.e = parseInt(public_exponent, 16);
4967 var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
4968 this.d = parseBigInt(private_exponent, 16);
4969 var prime1 = asn1.sub[4].getHexStringValue(); // bigint
4970 this.p = parseBigInt(prime1, 16);
4971 var prime2 = asn1.sub[5].getHexStringValue(); // bigint
4972 this.q = parseBigInt(prime2, 16);
4973 var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
4974 this.dmp1 = parseBigInt(exponent1, 16);
4975 var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
4976 this.dmq1 = parseBigInt(exponent2, 16);
4977 var coefficient = asn1.sub[8].getHexStringValue(); // bigint
4978 this.coeff = parseBigInt(coefficient, 16);
4980 else if (asn1.sub.length === 2) {
4981 // Parse the public key.
4982 var bit_string = asn1.sub[1];
4983 var sequence = bit_string.sub[0];
4984 modulus = sequence.sub[0].getHexStringValue();
4985 this.n = parseBigInt(modulus, 16);
4986 public_exponent = sequence.sub[1].getHexStringValue();
4987 this.e = parseInt(public_exponent, 16);
4999 * Translate rsa parameters in a hex encoded string representing the rsa key.
5001 * The translation follow the ASN.1 notation :
5002 * RSAPrivateKey ::= SEQUENCE {
5004 * modulus INTEGER, -- n
5005 * publicExponent INTEGER, -- e
5006 * privateExponent INTEGER, -- d
5007 * prime1 INTEGER, -- p
5008 * prime2 INTEGER, -- q
5009 * exponent1 INTEGER, -- d mod (p1)
5010 * exponent2 INTEGER, -- d mod (q-1)
5011 * coefficient INTEGER, -- (inverse of q) mod p
5013 * @returns {string} DER Encoded String representing the rsa private key
5016 JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
5019 new KJUR.asn1.DERInteger({ int: 0 }),
5020 new KJUR.asn1.DERInteger({ bigint: this.n }),
5021 new KJUR.asn1.DERInteger({ int: this.e }),
5022 new KJUR.asn1.DERInteger({ bigint: this.d }),
5023 new KJUR.asn1.DERInteger({ bigint: this.p }),
5024 new KJUR.asn1.DERInteger({ bigint: this.q }),
5025 new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
5026 new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
5027 new KJUR.asn1.DERInteger({ bigint: this.coeff })
5030 var seq = new KJUR.asn1.DERSequence(options);
5031 return seq.getEncodedHex();
5034 * base64 (pem) encoded version of the DER encoded representation
5035 * @returns {string} pem encoded representation without header and footer
5038 JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
5039 return hex2b64(this.getPrivateBaseKey());
5042 * Translate rsa parameters in a hex encoded string representing the rsa public key.
5043 * The representation follow the ASN.1 notation :
5044 * PublicKeyInfo ::= SEQUENCE {
5045 * algorithm AlgorithmIdentifier,
5046 * PublicKey BIT STRING
5048 * Where AlgorithmIdentifier is:
5049 * AlgorithmIdentifier ::= SEQUENCE {
5050 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
5051 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
5053 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
5054 * RSAPublicKey ::= SEQUENCE {
5055 * modulus INTEGER, -- n
5056 * publicExponent INTEGER -- e
5058 * @returns {string} DER Encoded String representing the rsa public key
5061 JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
5062 var first_sequence = new KJUR.asn1.DERSequence({
5064 new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
5065 new KJUR.asn1.DERNull()
5068 var second_sequence = new KJUR.asn1.DERSequence({
5070 new KJUR.asn1.DERInteger({ bigint: this.n }),
5071 new KJUR.asn1.DERInteger({ int: this.e })
5074 var bit_string = new KJUR.asn1.DERBitString({
5075 hex: "00" + second_sequence.getEncodedHex()
5077 var seq = new KJUR.asn1.DERSequence({
5083 return seq.getEncodedHex();
5086 * base64 (pem) encoded version of the DER encoded representation
5087 * @returns {string} pem encoded representation without header and footer
5090 JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
5091 return hex2b64(this.getPublicBaseKey());
5094 * wrap the string in block of width chars. The default value for rsa keys is 64
5096 * @param {string} str the pem encoded string without header and footer
5097 * @param {Number} [width=64] - the length the string has to be wrapped at
5101 JSEncryptRSAKey.wordwrap = function (str, width) {
5102 width = width || 64;
5106 var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
5107 return str.match(RegExp(regex, "g")).join("\n");
5110 * Retrieve the pem encoded private key
5111 * @returns {string} the pem encoded private key with header/footer
5114 JSEncryptRSAKey.prototype.getPrivateKey = function () {
5115 var key = "-----BEGIN RSA PRIVATE KEY-----\n";
5116 key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
5117 key += "-----END RSA PRIVATE KEY-----";
5121 * Retrieve the pem encoded public key
5122 * @returns {string} the pem encoded public key with header/footer
5125 JSEncryptRSAKey.prototype.getPublicKey = function () {
5126 var key = "-----BEGIN PUBLIC KEY-----\n";
5127 key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
5128 key += "-----END PUBLIC KEY-----";
5132 * Check if the object contains the necessary parameters to populate the rsa modulus
5133 * and public exponent parameters.
5134 * @param {Object} [obj={}] - An object that may contain the two public key
5136 * @returns {boolean} true if the object contains both the modulus and the public exponent
5137 * properties (n and e)
5138 * @todo check for types of n and e. N should be a parseable bigInt object, E should
5139 * be a parseable integer number
5142 JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
5144 return (obj.hasOwnProperty("n") &&
5145 obj.hasOwnProperty("e"));
5148 * Check if the object contains ALL the parameters of an RSA key.
5149 * @param {Object} [obj={}] - An object that may contain nine rsa key
5151 * @returns {boolean} true if the object contains all the parameters needed
5152 * @todo check for types of the parameters all the parameters but the public exponent
5153 * should be parseable bigint objects, the public exponent should be a parseable integer number
5156 JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
5158 return (obj.hasOwnProperty("n") &&
5159 obj.hasOwnProperty("e") &&
5160 obj.hasOwnProperty("d") &&
5161 obj.hasOwnProperty("p") &&
5162 obj.hasOwnProperty("q") &&
5163 obj.hasOwnProperty("dmp1") &&
5164 obj.hasOwnProperty("dmq1") &&
5165 obj.hasOwnProperty("coeff"));
5168 * Parse the properties of obj in the current rsa object. Obj should AT LEAST
5169 * include the modulus and public exponent (n, e) parameters.
5170 * @param {Object} obj - the object containing rsa parameters
5173 JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
5176 if (obj.hasOwnProperty("d")) {
5180 this.dmp1 = obj.dmp1;
5181 this.dmq1 = obj.dmq1;
5182 this.coeff = obj.coeff;
5185 return JSEncryptRSAKey;
5190 * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
5191 * possible parameters are:
5192 * - default_key_size {number} default: 1024 the key size in bit
5193 * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
5194 * - log {boolean} default: false whether log warn/error or not
5197 var JSEncrypt = /** @class */ (function () {
5198 function JSEncrypt(options) {
5199 options = options || {};
5200 this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
5201 this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
5202 this.log = options.log || false;
5203 // The private and public key.
5207 * Method to set the rsa key parameter (one method is enough to set both the public
5208 * and the private key, since the private key contains the public key paramenters)
5209 * Log a warning if logs are enabled
5210 * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
5213 JSEncrypt.prototype.setKey = function (key) {
5214 if (this.log && this.key) {
5215 console.warn("A key was already set, overriding existing.");
5217 this.key = new JSEncryptRSAKey(key);
5220 * Proxy method for setKey, for api compatibility
5224 JSEncrypt.prototype.setPrivateKey = function (privkey) {
5226 this.setKey(privkey);
5229 * Proxy method for setKey, for api compatibility
5233 JSEncrypt.prototype.setPublicKey = function (pubkey) {
5234 // Sets the public key.
5235 this.setKey(pubkey);
5238 * Proxy method for RSAKey object's decrypt, decrypt the string using the private
5239 * components of the rsa key object. Note that if the object was not set will be created
5240 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5241 * @param {string} str base64 encoded crypted string to decrypt
5242 * @return {string} the decrypted string
5245 JSEncrypt.prototype.decrypt = function (str) {
5246 // Return the decrypted string.
5248 return this.getKey().decrypt(b64tohex(str));
5255 * Proxy method for RSAKey object's encrypt, encrypt the string using the public
5256 * components of the rsa key object. Note that if the object was not set will be created
5257 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5258 * @param {string} str the string to encrypt
5259 * @return {string} the encrypted string encoded in base64
5262 JSEncrypt.prototype.encrypt = function (str) {
5263 // Return the encrypted string.
5265 return hex2b64(this.getKey().encrypt(str));
5272 * Proxy method for RSAKey object's sign.
5273 * @param {string} str the string to sign
5274 * @param {function} digestMethod hash method
5275 * @param {string} digestName the name of the hash algorithm
5276 * @return {string} the signature encoded in base64
5279 JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
5280 // return the RSA signature of 'str' in 'hex' format.
5282 return hex2b64(this.getKey().sign(str, digestMethod, digestName));
5289 * Proxy method for RSAKey object's verify.
5290 * @param {string} str the string to verify
5291 * @param {string} signature the signature encoded in base64 to compare the string to
5292 * @param {function} digestMethod hash method
5293 * @return {boolean} whether the data and signature match
5296 JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
5297 // Return the decrypted 'digest' of the signature.
5299 return this.getKey().verify(str, b64tohex(signature), digestMethod);
5306 * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
5307 * will be created and returned
5308 * @param {callback} [cb] the callback to be called if we want the key to be generated
5309 * in an async fashion
5310 * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
5313 JSEncrypt.prototype.getKey = function (cb) {
5314 // Only create new if it does not exist.
5316 // Get a new private key.
5317 this.key = new JSEncryptRSAKey();
5318 if (cb && {}.toString.call(cb) === "[object Function]") {
5319 this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
5322 // Generate the key.
5323 this.key.generate(this.default_key_size, this.default_public_exponent);
5328 * Returns the pem encoded representation of the private key
5329 * If the key doesn't exists a new key will be created
5330 * @returns {string} pem encoded representation of the private key WITH header and footer
5333 JSEncrypt.prototype.getPrivateKey = function () {
5334 // Return the private representation of this key.
5335 return this.getKey().getPrivateKey();
5338 * Returns the pem encoded representation of the private key
5339 * If the key doesn't exists a new key will be created
5340 * @returns {string} pem encoded representation of the private key WITHOUT header and footer
5343 JSEncrypt.prototype.getPrivateKeyB64 = function () {
5344 // Return the private representation of this key.
5345 return this.getKey().getPrivateBaseKeyB64();
5348 * Returns the pem encoded representation of the public key
5349 * If the key doesn't exists a new key will be created
5350 * @returns {string} pem encoded representation of the public key WITH header and footer
5353 JSEncrypt.prototype.getPublicKey = function () {
5354 // Return the private representation of this key.
5355 return this.getKey().getPublicKey();
5358 * Returns the pem encoded representation of the public key
5359 * If the key doesn't exists a new key will be created
5360 * @returns {string} pem encoded representation of the public key WITHOUT header and footer
5363 JSEncrypt.prototype.getPublicKeyB64 = function () {
5364 // Return the private representation of this key.
5365 return this.getKey().getPublicBaseKeyB64();
5367 JSEncrypt.version = "3.0.0-rc.1";
5371 window.JSEncrypt = JSEncrypt;
5373 exports.JSEncrypt = JSEncrypt;
5374 exports.default = JSEncrypt;
5376 Object.defineProperty(exports, '__esModule', { value: true });