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 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
9 Math.random = function() {
10 const byteArray = new Uint32Array(1);
11 return (window.crypto.getRandomValues(byteArray))[0];
14 function int2char(n) {
15 return BI_RM.charAt(n);
17 //#region BIT_OPERATIONS
19 function op_and(x, y) {
23 function op_or(x, y) {
27 function op_xor(x, y) {
31 function op_andnot(x, y) {
34 // return index of lowest 1-bit in x, x < 2^31
40 if ((x & 0xffff) == 0) {
44 if ((x & 0xff) == 0) {
61 // return number of 1 bits in x
70 //#endregion BIT_OPERATIONS
72 var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
78 for (i = 0; i + 3 <= h.length; i += 3) {
79 c = parseInt(h.substring(i, i + 3), 16);
80 ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
82 if (i + 1 == h.length) {
83 c = parseInt(h.substring(i, i + 1), 16);
84 ret += b64map.charAt(c << 2);
86 else if (i + 2 == h.length) {
87 c = parseInt(h.substring(i, i + 2), 16);
88 ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
90 while ((ret.length & 3) > 0) {
95 // convert a base64 string to hex
96 function b64tohex(s) {
99 var k = 0; // b64 state, 0-3
101 for (i = 0; i < s.length; ++i) {
102 if (s.charAt(i) == b64pad) {
105 var v = b64map.indexOf(s.charAt(i));
110 ret += int2char(v >> 2);
115 ret += int2char((slop << 2) | (v >> 4));
120 ret += int2char(slop);
121 ret += int2char(v >> 2);
126 ret += int2char((slop << 2) | (v >> 4));
127 ret += int2char(v & 0xf);
132 ret += int2char(slop << 2);
137 /*! *****************************************************************************
138 Copyright (c) Microsoft Corporation. All rights reserved.
139 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
140 this file except in compliance with the License. You may obtain a copy of the
141 License at http://www.apache.org/licenses/LICENSE-2.0
142 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
143 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
144 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
145 MERCHANTABLITY OR NON-INFRINGEMENT.
146 See the Apache Version 2.0 License for specific language governing permissions
147 and limitations under the License.
148 ***************************************************************************** */
149 /* global Reflect, Promise */
151 var extendStatics = function(d, b) {
152 extendStatics = Object.setPrototypeOf ||
153 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
154 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
155 return extendStatics(d, b);
158 function __extends(d, b) {
160 function __() { this.constructor = d; }
161 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
164 // Hex JavaScript decoder
165 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
166 // Permission to use, copy, modify, and/or distribute this software for any
167 // purpose with or without fee is hereby granted, provided that the above
168 // copyright notice and this permission notice appear in all copies.
170 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
171 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
172 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
173 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
174 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
175 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
176 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
177 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
180 decode: function (a) {
182 if (decoder === undefined) {
183 var hex = "0123456789ABCDEF";
184 var ignore = " \f\n\r\t\u00A0\u2028\u2029";
186 for (i = 0; i < 16; ++i) {
187 decoder[hex.charAt(i)] = i;
189 hex = hex.toLowerCase();
190 for (i = 10; i < 16; ++i) {
191 decoder[hex.charAt(i)] = i;
193 for (i = 0; i < ignore.length; ++i) {
194 decoder[ignore.charAt(i)] = -1;
200 for (i = 0; i < a.length; ++i) {
209 if (c === undefined) {
210 throw new Error("Illegal character at offset " + i);
213 if (++char_count >= 2) {
214 out[out.length] = bits;
223 throw new Error("Hex encoding incomplete: 4 bits missing");
229 // Base64 JavaScript decoder
230 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
231 // Permission to use, copy, modify, and/or distribute this software for any
232 // purpose with or without fee is hereby granted, provided that the above
233 // copyright notice and this permission notice appear in all copies.
235 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
236 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
237 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
238 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
239 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
240 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
241 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
242 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
245 decode: function (a) {
247 if (decoder$1 === undefined) {
248 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
249 var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
250 decoder$1 = Object.create(null);
251 for (i = 0; i < 64; ++i) {
252 decoder$1[b64.charAt(i)] = i;
254 for (i = 0; i < ignore.length; ++i) {
255 decoder$1[ignore.charAt(i)] = -1;
261 for (i = 0; i < a.length; ++i) {
270 if (c === undefined) {
271 throw new Error("Illegal character at offset " + i);
274 if (++char_count >= 4) {
275 out[out.length] = (bits >> 16);
276 out[out.length] = (bits >> 8) & 0xFF;
277 out[out.length] = bits & 0xFF;
285 switch (char_count) {
287 throw new Error("Base64 encoding incomplete: at least 2 bits missing");
289 out[out.length] = (bits >> 10);
292 out[out.length] = (bits >> 16);
293 out[out.length] = (bits >> 8) & 0xFF;
298 re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
299 unarmor: function (a) {
300 var m = Base64.re.exec(a);
309 throw new Error("RegExp out of sync");
312 return Base64.decode(a);
316 // Big integer base-10 printing library
317 // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
318 // Permission to use, copy, modify, and/or distribute this software for any
319 // purpose with or without fee is hereby granted, provided that the above
320 // copyright notice and this permission notice appear in all copies.
322 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
323 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
324 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
325 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
326 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
327 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
328 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
329 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
330 var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
331 var Int10 = /** @class */ (function () {
332 function Int10(value) {
333 this.buf = [+value || 0];
335 Int10.prototype.mulAdd = function (m, c) {
341 for (i = 0; i < l; ++i) {
356 Int10.prototype.sub = function (c) {
362 for (i = 0; i < l; ++i) {
373 while (b[b.length - 1] === 0) {
377 Int10.prototype.toString = function (base) {
378 if ((base || 10) != 10) {
379 throw new Error("only base 10 is supported");
382 var s = b[b.length - 1].toString();
383 for (var i = b.length - 2; i >= 0; --i) {
384 s += (max + b[i]).toString().substring(1);
388 Int10.prototype.valueOf = function () {
391 for (var i = b.length - 1; i >= 0; --i) {
396 Int10.prototype.simplify = function () {
398 return (b.length == 1) ? b[0] : this;
403 // ASN.1 JavaScript decoder
404 var ellipsis = "\u2026";
405 var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
406 var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
407 function stringCut(str, len) {
408 if (str.length > len) {
409 str = str.substring(0, len) + ellipsis;
413 var Stream = /** @class */ (function () {
414 function Stream(enc, pos) {
415 this.hexDigits = "0123456789ABCDEF";
416 if (enc instanceof Stream) {
421 // enc should be an array or a binary string
426 Stream.prototype.get = function (pos) {
427 if (pos === undefined) {
430 if (pos >= this.enc.length) {
431 throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
433 return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
435 Stream.prototype.hexByte = function (b) {
436 return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
438 Stream.prototype.hexDump = function (start, end, raw) {
440 for (var i = start; i < end; ++i) {
441 s += this.hexByte(this.get(i));
457 Stream.prototype.isASCII = function (start, end) {
458 for (var i = start; i < end; ++i) {
460 if (c < 32 || c > 176) {
466 Stream.prototype.parseStringISO = function (start, end) {
468 for (var i = start; i < end; ++i) {
469 s += String.fromCharCode(this.get(i));
473 Stream.prototype.parseStringUTF = function (start, end) {
475 for (var i = start; i < end;) {
476 var c = this.get(i++);
478 s += String.fromCharCode(c);
480 else if ((c > 191) && (c < 224)) {
481 s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
484 s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
489 Stream.prototype.parseStringBMP = function (start, end) {
493 for (var i = start; i < end;) {
496 str += String.fromCharCode((hi << 8) | lo);
500 Stream.prototype.parseTime = function (start, end, shortYear) {
501 var s = this.parseStringISO(start, end);
502 var m = (shortYear ? reTimeS : reTimeL).exec(s);
504 return "Unrecognized time: " + s;
507 // to avoid querying the timer, use the fixed range [1970, 2069]
508 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
510 m[1] += (+m[1] < 70) ? 2000 : 1900;
512 s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
533 Stream.prototype.parseInteger = function (start, end) {
534 var v = this.get(start);
536 var pad = neg ? 255 : 0;
539 // skip unuseful bits (not allowed in DER)
540 while (v == pad && ++start < end) {
547 // show bit length of huge integers
551 while (((+s ^ pad) & 0x80) == 0) {
555 s = "(" + len + " bit)\n";
557 // decode the integer
561 var n = new Int10(v);
562 for (var i = start + 1; i < end; ++i) {
563 n.mulAdd(256, this.get(i));
565 return s + n.toString();
567 Stream.prototype.parseBitString = function (start, end, maxLength) {
568 var unusedBit = this.get(start);
569 var lenBit = ((end - start - 1) << 3) - unusedBit;
570 var intro = "(" + lenBit + " bit)\n";
572 for (var i = start + 1; i < end; ++i) {
574 var skip = (i == end - 1) ? unusedBit : 0;
575 for (var j = 7; j >= skip; --j) {
576 s += (b >> j) & 1 ? "1" : "0";
578 if (s.length > maxLength) {
579 return intro + stringCut(s, maxLength);
584 Stream.prototype.parseOctetString = function (start, end, maxLength) {
585 if (this.isASCII(start, end)) {
586 return stringCut(this.parseStringISO(start, end), maxLength);
588 var len = end - start;
589 var s = "(" + len + " byte)\n";
590 maxLength /= 2; // we work in bytes
591 if (len > maxLength) {
592 end = start + maxLength;
594 for (var i = start; i < end; ++i) {
595 s += this.hexByte(this.get(i));
597 if (len > maxLength) {
602 Stream.prototype.parseOID = function (start, end, maxLength) {
606 for (var i = start; i < end; ++i) {
608 n.mulAdd(128, v & 0x7F);
610 if (!(v & 0x80)) { // finished
613 if (n instanceof Int10) {
615 s = "2." + n.toString();
618 var m = n < 80 ? n < 40 ? 0 : 1 : 2;
619 s = m + "." + (n - m * 40);
623 s += "." + n.toString();
625 if (s.length > maxLength) {
626 return stringCut(s, maxLength);
639 var ASN1 = /** @class */ (function () {
640 function ASN1(stream, header, length, tag, sub) {
641 if (!(tag instanceof ASN1Tag)) {
642 throw new Error("Invalid tag value.");
644 this.stream = stream;
645 this.header = header;
646 this.length = length;
650 ASN1.prototype.typeName = function () {
651 switch (this.tag.tagClass) {
653 switch (this.tag.tagNumber) {
663 return "OCTET_STRING";
667 return "OBJECT_IDENTIFIER";
669 return "ObjectDescriptor";
677 return "EMBEDDED_PDV";
685 return "NumericString";
687 return "PrintableString"; // ASCII subset
689 return "TeletexString"; // aka T61String
691 return "VideotexString";
693 return "IA5String"; // ASCII
697 return "GeneralizedTime";
699 return "GraphicString";
701 return "VisibleString"; // ASCII subset
703 return "GeneralString";
705 return "UniversalString";
709 return "Universal_" + this.tag.tagNumber.toString();
711 return "Application_" + this.tag.tagNumber.toString();
713 return "[" + this.tag.tagNumber.toString() + "]"; // Context
715 return "Private_" + this.tag.tagNumber.toString();
718 ASN1.prototype.content = function (maxLength) {
719 if (this.tag === undefined) {
722 if (maxLength === undefined) {
723 maxLength = Infinity;
725 var content = this.posContent();
726 var len = Math.abs(this.length);
727 if (!this.tag.isUniversal()) {
728 if (this.sub !== null) {
729 return "(" + this.sub.length + " elem)";
731 return this.stream.parseOctetString(content, content + len, maxLength);
733 switch (this.tag.tagNumber) {
734 case 0x01: // BOOLEAN
735 return (this.stream.get(content) === 0) ? "false" : "true";
736 case 0x02: // INTEGER
737 return this.stream.parseInteger(content, content + len);
738 case 0x03: // BIT_STRING
739 return this.sub ? "(" + this.sub.length + " elem)" :
740 this.stream.parseBitString(content, content + len, maxLength);
741 case 0x04: // OCTET_STRING
742 return this.sub ? "(" + this.sub.length + " elem)" :
743 this.stream.parseOctetString(content, content + len, maxLength);
744 // case 0x05: // NULL
745 case 0x06: // OBJECT_IDENTIFIER
746 return this.stream.parseOID(content, content + len, maxLength);
747 // case 0x07: // ObjectDescriptor
748 // case 0x08: // EXTERNAL
749 // case 0x09: // REAL
750 // case 0x0A: // ENUMERATED
751 // case 0x0B: // EMBEDDED_PDV
752 case 0x10: // SEQUENCE
754 if (this.sub !== null) {
755 return "(" + this.sub.length + " elem)";
760 case 0x0C: // UTF8String
761 return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
762 case 0x12: // NumericString
763 case 0x13: // PrintableString
764 case 0x14: // TeletexString
765 case 0x15: // VideotexString
766 case 0x16: // IA5String
767 // case 0x19: // GraphicString
768 case 0x1A: // VisibleString
769 // case 0x1B: // GeneralString
770 // case 0x1C: // UniversalString
771 return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
772 case 0x1E: // BMPString
773 return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
774 case 0x17: // UTCTime
775 case 0x18: // GeneralizedTime
776 return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
780 ASN1.prototype.toString = function () {
781 return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
783 ASN1.prototype.toPrettyString = function (indent) {
784 if (indent === undefined) {
787 var s = indent + this.typeName() + " @" + this.stream.pos;
788 if (this.length >= 0) {
792 if (this.tag.tagConstructed) {
793 s += " (constructed)";
795 else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
796 s += " (encapsulates)";
799 if (this.sub !== null) {
801 for (var i = 0, max = this.sub.length; i < max; ++i) {
802 s += this.sub[i].toPrettyString(indent);
807 ASN1.prototype.posStart = function () {
808 return this.stream.pos;
810 ASN1.prototype.posContent = function () {
811 return this.stream.pos + this.header;
813 ASN1.prototype.posEnd = function () {
814 return this.stream.pos + this.header + Math.abs(this.length);
816 ASN1.prototype.toHexString = function () {
817 return this.stream.hexDump(this.posStart(), this.posEnd(), true);
819 ASN1.decodeLength = function (stream) {
820 var buf = stream.get();
821 var len = buf & 0x7F;
825 // no reason to use Int10, as it would be a huge buffer anyways
827 throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
833 for (var i = 0; i < len; ++i) {
834 buf = (buf * 256) + stream.get();
839 * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
843 ASN1.prototype.getHexStringValue = function () {
844 var hexString = this.toHexString();
845 var offset = this.header * 2;
846 var length = this.length * 2;
847 return hexString.substr(offset, length);
849 ASN1.decode = function (str) {
851 if (!(str instanceof Stream)) {
852 stream = new Stream(str, 0);
857 var streamStart = new Stream(stream);
858 var tag = new ASN1Tag(stream);
859 var len = ASN1.decodeLength(stream);
860 var start = stream.pos;
861 var header = start - streamStart.pos;
863 var getSub = function () {
867 var end = start + len;
868 while (stream.pos < end) {
869 ret[ret.length] = ASN1.decode(stream);
871 if (stream.pos != end) {
872 throw new Error("Content size is not correct for container starting at offset " + start);
879 var s = ASN1.decode(stream);
885 len = start - stream.pos; // undefined lengths are represented as negative values
888 throw new Error("Exception while decoding undefined length content: " + e);
893 if (tag.tagConstructed) {
894 // must have valid content
897 else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
898 // sometimes BitString and OctetString are used to encapsulate ASN.1
900 if (tag.tagNumber == 0x03) {
901 if (stream.get() != 0) {
902 throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
906 for (var i = 0; i < sub.length; ++i) {
907 if (sub[i].tag.isEOC()) {
908 throw new Error("EOC is not supposed to be actual content.");
913 // but silently ignore when they don't
919 throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
921 stream.pos = start + Math.abs(len);
923 return new ASN1(streamStart, header, len, tag, sub);
927 var ASN1Tag = /** @class */ (function () {
928 function ASN1Tag(stream) {
929 var buf = stream.get();
930 this.tagClass = buf >> 6;
931 this.tagConstructed = ((buf & 0x20) !== 0);
932 this.tagNumber = buf & 0x1F;
933 if (this.tagNumber == 0x1F) { // long tag
937 n.mulAdd(128, buf & 0x7F);
938 } while (buf & 0x80);
939 this.tagNumber = n.simplify();
942 ASN1Tag.prototype.isUniversal = function () {
943 return this.tagClass === 0x00;
945 ASN1Tag.prototype.isEOC = function () {
946 return this.tagClass === 0x00 && this.tagNumber === 0x00;
951 // Copyright (c) 2005 Tom Wu
954 // JavaScript engine analysis
955 var canary = 0xdeadbeefcafe;
956 var j_lm = ((canary & 0xffffff) == 0xefcafe);
958 var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
959 var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
961 // (public) Constructor
962 var BigInteger = /** @class */ (function () {
963 function BigInteger(a, b, c) {
965 if ("number" == typeof a) {
966 this.fromNumber(a, b, c);
968 else if (b == null && "string" != typeof a) {
969 this.fromString(a, 256);
972 this.fromString(a, b);
977 // BigInteger.prototype.toString = bnToString;
978 // (public) return string representation in given radix
979 BigInteger.prototype.toString = function (b) {
981 return "-" + this.negate().toString(b);
1000 return this.toRadix(b);
1002 var km = (1 << k) - 1;
1007 var p = this.DB - (i * this.DB) % k;
1009 if (p < this.DB && (d = this[i] >> p) > 0) {
1015 d = (this[i] & ((1 << p) - 1)) << (k - p);
1016 d |= this[--i] >> (p += this.DB - k);
1019 d = (this[i] >> (p -= k)) & km;
1035 // BigInteger.prototype.negate = bnNegate;
1037 BigInteger.prototype.negate = function () {
1039 BigInteger.ZERO.subTo(this, r);
1042 // BigInteger.prototype.abs = bnAbs;
1044 BigInteger.prototype.abs = function () {
1045 return (this.s < 0) ? this.negate() : this;
1047 // BigInteger.prototype.compareTo = bnCompareTo;
1048 // (public) return + if this > a, - if this < a, 0 if equal
1049 BigInteger.prototype.compareTo = function (a) {
1050 var r = this.s - a.s;
1057 return (this.s < 0) ? -r : r;
1060 if ((r = this[i] - a[i]) != 0) {
1066 // BigInteger.prototype.bitLength = bnBitLength;
1067 // (public) return the number of bits in "this"
1068 BigInteger.prototype.bitLength = function () {
1072 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
1074 // BigInteger.prototype.mod = bnMod;
1075 // (public) this mod a
1076 BigInteger.prototype.mod = function (a) {
1078 this.abs().divRemTo(a, null, r);
1079 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
1084 // BigInteger.prototype.modPowInt = bnModPowInt;
1085 // (public) this^e % m, 0 <= e < 2^32
1086 BigInteger.prototype.modPowInt = function (e, m) {
1088 if (e < 256 || m.isEven()) {
1092 z = new Montgomery(m);
1094 return this.exp(e, z);
1096 // BigInteger.prototype.clone = bnClone;
1098 BigInteger.prototype.clone = function () {
1103 // BigInteger.prototype.intValue = bnIntValue;
1104 // (public) return value as integer
1105 BigInteger.prototype.intValue = function () {
1108 return this[0] - this.DV;
1110 else if (this.t == 0) {
1114 else if (this.t == 1) {
1117 else if (this.t == 0) {
1120 // assumes 16 < DB < 32
1121 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
1123 // BigInteger.prototype.byteValue = bnByteValue;
1124 // (public) return value as byte
1125 BigInteger.prototype.byteValue = function () {
1126 return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
1128 // BigInteger.prototype.shortValue = bnShortValue;
1129 // (public) return value as short (assumes DB>=16)
1130 BigInteger.prototype.shortValue = function () {
1131 return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
1133 // BigInteger.prototype.signum = bnSigNum;
1134 // (public) 0 if this == 0, 1 if this > 0
1135 BigInteger.prototype.signum = function () {
1139 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
1146 // BigInteger.prototype.toByteArray = bnToByteArray;
1147 // (public) convert to bigendian byte array
1148 BigInteger.prototype.toByteArray = function () {
1152 var p = this.DB - (i * this.DB) % 8;
1156 if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
1157 r[k++] = d | (this.s << (this.DB - p));
1161 d = (this[i] & ((1 << p) - 1)) << (8 - p);
1162 d |= this[--i] >> (p += this.DB - 8);
1165 d = (this[i] >> (p -= 8)) & 0xff;
1171 if ((d & 0x80) != 0) {
1174 if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
1177 if (k > 0 || d != this.s) {
1184 // BigInteger.prototype.equals = bnEquals;
1185 BigInteger.prototype.equals = function (a) {
1186 return (this.compareTo(a) == 0);
1188 // BigInteger.prototype.min = bnMin;
1189 BigInteger.prototype.min = function (a) {
1190 return (this.compareTo(a) < 0) ? this : a;
1192 // BigInteger.prototype.max = bnMax;
1193 BigInteger.prototype.max = function (a) {
1194 return (this.compareTo(a) > 0) ? this : a;
1196 // BigInteger.prototype.and = bnAnd;
1197 BigInteger.prototype.and = function (a) {
1199 this.bitwiseTo(a, op_and, r);
1202 // BigInteger.prototype.or = bnOr;
1203 BigInteger.prototype.or = function (a) {
1205 this.bitwiseTo(a, op_or, r);
1208 // BigInteger.prototype.xor = bnXor;
1209 BigInteger.prototype.xor = function (a) {
1211 this.bitwiseTo(a, op_xor, r);
1214 // BigInteger.prototype.andNot = bnAndNot;
1215 BigInteger.prototype.andNot = function (a) {
1217 this.bitwiseTo(a, op_andnot, r);
1220 // BigInteger.prototype.not = bnNot;
1222 BigInteger.prototype.not = function () {
1224 for (var i = 0; i < this.t; ++i) {
1225 r[i] = this.DM & ~this[i];
1231 // BigInteger.prototype.shiftLeft = bnShiftLeft;
1232 // (public) this << n
1233 BigInteger.prototype.shiftLeft = function (n) {
1236 this.rShiftTo(-n, r);
1239 this.lShiftTo(n, r);
1243 // BigInteger.prototype.shiftRight = bnShiftRight;
1244 // (public) this >> n
1245 BigInteger.prototype.shiftRight = function (n) {
1248 this.lShiftTo(-n, r);
1251 this.rShiftTo(n, r);
1255 // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
1256 // (public) returns index of lowest 1-bit (or -1 if none)
1257 BigInteger.prototype.getLowestSetBit = function () {
1258 for (var i = 0; i < this.t; ++i) {
1260 return i * this.DB + lbit(this[i]);
1264 return this.t * this.DB;
1268 // BigInteger.prototype.bitCount = bnBitCount;
1269 // (public) return number of set bits
1270 BigInteger.prototype.bitCount = function () {
1272 var x = this.s & this.DM;
1273 for (var i = 0; i < this.t; ++i) {
1274 r += cbit(this[i] ^ x);
1278 // BigInteger.prototype.testBit = bnTestBit;
1279 // (public) true iff nth bit is set
1280 BigInteger.prototype.testBit = function (n) {
1281 var j = Math.floor(n / this.DB);
1283 return (this.s != 0);
1285 return ((this[j] & (1 << (n % this.DB))) != 0);
1287 // BigInteger.prototype.setBit = bnSetBit;
1288 // (public) this | (1<<n)
1289 BigInteger.prototype.setBit = function (n) {
1290 return this.changeBit(n, op_or);
1292 // BigInteger.prototype.clearBit = bnClearBit;
1293 // (public) this & ~(1<<n)
1294 BigInteger.prototype.clearBit = function (n) {
1295 return this.changeBit(n, op_andnot);
1297 // BigInteger.prototype.flipBit = bnFlipBit;
1298 // (public) this ^ (1<<n)
1299 BigInteger.prototype.flipBit = function (n) {
1300 return this.changeBit(n, op_xor);
1302 // BigInteger.prototype.add = bnAdd;
1303 // (public) this + a
1304 BigInteger.prototype.add = function (a) {
1309 // BigInteger.prototype.subtract = bnSubtract;
1310 // (public) this - a
1311 BigInteger.prototype.subtract = function (a) {
1316 // BigInteger.prototype.multiply = bnMultiply;
1317 // (public) this * a
1318 BigInteger.prototype.multiply = function (a) {
1320 this.multiplyTo(a, r);
1323 // BigInteger.prototype.divide = bnDivide;
1324 // (public) this / a
1325 BigInteger.prototype.divide = function (a) {
1327 this.divRemTo(a, r, null);
1330 // BigInteger.prototype.remainder = bnRemainder;
1331 // (public) this % a
1332 BigInteger.prototype.remainder = function (a) {
1334 this.divRemTo(a, null, r);
1337 // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
1338 // (public) [this/a,this%a]
1339 BigInteger.prototype.divideAndRemainder = function (a) {
1342 this.divRemTo(a, q, r);
1345 // BigInteger.prototype.modPow = bnModPow;
1346 // (public) this^e % m (HAC 14.85)
1347 BigInteger.prototype.modPow = function (e, m) {
1348 var i = e.bitLength();
1373 else if (m.isEven()) {
1377 z = new Montgomery(m);
1383 var km = (1 << k) - 1;
1384 g[1] = z.convert(this);
1390 z.mulTo(g2, g[n - 2], g[n]);
1399 i = nbits(e[j]) - 1;
1402 w = (e[j] >> (i - k1)) & km;
1405 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
1407 w |= e[j - 1] >> (this.DB + i - k1);
1411 while ((w & 1) == 0) {
1419 if (is1) { // ret == 1, don't bother squaring or multiplying it
1437 z.mulTo(r2, g[w], r);
1439 while (j >= 0 && (e[j] & (1 << i)) == 0) {
1452 // BigInteger.prototype.modInverse = bnModInverse;
1453 // (public) 1/this % m (HAC 14.61)
1454 BigInteger.prototype.modInverse = function (m) {
1455 var ac = m.isEven();
1456 if ((this.isEven() && ac) || m.signum() == 0) {
1457 return BigInteger.ZERO;
1460 var v = this.clone();
1465 while (u.signum() != 0) {
1466 while (u.isEven()) {
1469 if (!a.isEven() || !b.isEven()) {
1475 else if (!b.isEven()) {
1480 while (v.isEven()) {
1483 if (!c.isEven() || !d.isEven()) {
1489 else if (!d.isEven()) {
1494 if (u.compareTo(v) >= 0) {
1509 if (v.compareTo(BigInteger.ONE) != 0) {
1510 return BigInteger.ZERO;
1512 if (d.compareTo(m) >= 0) {
1513 return d.subtract(m);
1515 if (d.signum() < 0) {
1521 if (d.signum() < 0) {
1528 // BigInteger.prototype.pow = bnPow;
1530 BigInteger.prototype.pow = function (e) {
1531 return this.exp(e, new NullExp());
1533 // BigInteger.prototype.gcd = bnGCD;
1534 // (public) gcd(this,a) (HAC 14.54)
1535 BigInteger.prototype.gcd = function (a) {
1536 var x = (this.s < 0) ? this.negate() : this.clone();
1537 var y = (a.s < 0) ? a.negate() : a.clone();
1538 if (x.compareTo(y) < 0) {
1543 var i = x.getLowestSetBit();
1544 var g = y.getLowestSetBit();
1555 while (x.signum() > 0) {
1556 if ((i = x.getLowestSetBit()) > 0) {
1559 if ((i = y.getLowestSetBit()) > 0) {
1562 if (x.compareTo(y) >= 0) {
1576 // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
1577 // (public) test primality with certainty >= 1-.5^t
1578 BigInteger.prototype.isProbablePrime = function (t) {
1581 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
1582 for (i = 0; i < lowprimes.length; ++i) {
1583 if (x[0] == lowprimes[i]) {
1593 while (i < lowprimes.length) {
1594 var m = lowprimes[i];
1596 while (j < lowprimes.length && m < lplim) {
1597 m *= lowprimes[j++];
1601 if (m % lowprimes[i++] == 0) {
1606 return x.millerRabin(t);
1610 // BigInteger.prototype.copyTo = bnpCopyTo;
1611 // (protected) copy this to r
1612 BigInteger.prototype.copyTo = function (r) {
1613 for (var i = this.t - 1; i >= 0; --i) {
1619 // BigInteger.prototype.fromInt = bnpFromInt;
1620 // (protected) set from integer value x, -DV <= x < DV
1621 BigInteger.prototype.fromInt = function (x) {
1623 this.s = (x < 0) ? -1 : 0;
1628 this[0] = x + this.DV;
1634 // BigInteger.prototype.fromString = bnpFromString;
1635 // (protected) set from string and radix
1636 BigInteger.prototype.fromString = function (s, b) {
1644 else if (b == 256) {
1658 this.fromRadix(s, b);
1667 var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
1669 if (s.charAt(i) == "-") {
1678 else if (sh + k > this.DB) {
1679 this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
1680 this[this.t++] = (x >> (this.DB - sh));
1683 this[this.t - 1] |= x << sh;
1686 if (sh >= this.DB) {
1690 if (k == 8 && ((+s[0]) & 0x80) != 0) {
1693 this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
1698 BigInteger.ZERO.subTo(this, this);
1701 // BigInteger.prototype.clamp = bnpClamp;
1702 // (protected) clamp off excess high words
1703 BigInteger.prototype.clamp = function () {
1704 var c = this.s & this.DM;
1705 while (this.t > 0 && this[this.t - 1] == c) {
1709 // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
1710 // (protected) r = this << n*DB
1711 BigInteger.prototype.dlShiftTo = function (n, r) {
1713 for (i = this.t - 1; i >= 0; --i) {
1716 for (i = n - 1; i >= 0; --i) {
1722 // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
1723 // (protected) r = this >> n*DB
1724 BigInteger.prototype.drShiftTo = function (n, r) {
1725 for (var i = n; i < this.t; ++i) {
1728 r.t = Math.max(this.t - n, 0);
1731 // BigInteger.prototype.lShiftTo = bnpLShiftTo;
1732 // (protected) r = this << n
1733 BigInteger.prototype.lShiftTo = function (n, r) {
1734 var bs = n % this.DB;
1735 var cbs = this.DB - bs;
1736 var bm = (1 << cbs) - 1;
1737 var ds = Math.floor(n / this.DB);
1738 var c = (this.s << bs) & this.DM;
1739 for (var i = this.t - 1; i >= 0; --i) {
1740 r[i + ds + 1] = (this[i] >> cbs) | c;
1741 c = (this[i] & bm) << bs;
1743 for (var i = ds - 1; i >= 0; --i) {
1747 r.t = this.t + ds + 1;
1751 // BigInteger.prototype.rShiftTo = bnpRShiftTo;
1752 // (protected) r = this >> n
1753 BigInteger.prototype.rShiftTo = function (n, r) {
1755 var ds = Math.floor(n / this.DB);
1760 var bs = n % this.DB;
1761 var cbs = this.DB - bs;
1762 var bm = (1 << bs) - 1;
1763 r[0] = this[ds] >> bs;
1764 for (var i = ds + 1; i < this.t; ++i) {
1765 r[i - ds - 1] |= (this[i] & bm) << cbs;
1766 r[i - ds] = this[i] >> bs;
1769 r[this.t - ds - 1] |= (this.s & bm) << cbs;
1774 // BigInteger.prototype.subTo = bnpSubTo;
1775 // (protected) r = this - a
1776 BigInteger.prototype.subTo = function (a, r) {
1779 var m = Math.min(a.t, this.t);
1781 c += this[i] - a[i];
1782 r[i++] = c & this.DM;
1787 while (i < this.t) {
1789 r[i++] = c & this.DM;
1798 r[i++] = c & this.DM;
1803 r.s = (c < 0) ? -1 : 0;
1805 r[i++] = this.DV + c;
1813 // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
1814 // (protected) r = this * a, r != this,a (HAC 14.12)
1815 // "this" should be the larger one if appropriate.
1816 BigInteger.prototype.multiplyTo = function (a, r) {
1824 for (i = 0; i < y.t; ++i) {
1825 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
1829 if (this.s != a.s) {
1830 BigInteger.ZERO.subTo(r, r);
1833 // BigInteger.prototype.squareTo = bnpSquareTo;
1834 // (protected) r = this^2, r != this (HAC 14.16)
1835 BigInteger.prototype.squareTo = function (r) {
1837 var i = r.t = 2 * x.t;
1841 for (i = 0; i < x.t - 1; ++i) {
1842 var c = x.am(i, x[i], r, 2 * i, 0, 1);
1843 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
1849 r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
1854 // BigInteger.prototype.divRemTo = bnpDivRemTo;
1855 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
1856 // r != q, this != m. q or r may be null.
1857 BigInteger.prototype.divRemTo = function (m, q, r) {
1862 var pt = this.abs();
1878 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
1880 pm.lShiftTo(nsh, y);
1881 pt.lShiftTo(nsh, r);
1892 var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
1893 var d1 = this.FV / yt;
1894 var d2 = (1 << this.F1) / yt;
1895 var e = 1 << this.F2;
1898 var t = (q == null) ? nbi() : q;
1900 if (r.compareTo(t) >= 0) {
1904 BigInteger.ONE.dlShiftTo(ys, t);
1905 t.subTo(y, y); // "negative" y so we can replace sub with am later
1910 // Estimate quotient digit
1911 var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
1912 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
1915 while (r[i] < --qd) {
1923 BigInteger.ZERO.subTo(q, q);
1930 } // Denormalize remainder
1932 BigInteger.ZERO.subTo(r, r);
1935 // BigInteger.prototype.invDigit = bnpInvDigit;
1936 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
1940 // xy(2-xy) = (1+km)(1-km)
1941 // x[y(2-xy)] = 1-k^2m^2
1942 // x[y(2-xy)] == 1 (mod m^2)
1943 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
1944 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
1945 // JS multiply "overflows" differently from C/C++, so care is needed here.
1946 BigInteger.prototype.invDigit = function () {
1954 var y = x & 3; // y == 1/x mod 2^2
1955 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
1956 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
1957 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
1958 // last step - calculate inverse mod DV directly;
1959 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
1960 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
1961 // we really want the negative inverse, and -DV < y < DV
1962 return (y > 0) ? this.DV - y : -y;
1964 // BigInteger.prototype.isEven = bnpIsEven;
1965 // (protected) true iff this is even
1966 BigInteger.prototype.isEven = function () {
1967 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
1969 // BigInteger.prototype.exp = bnpExp;
1970 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
1971 BigInteger.prototype.exp = function (e, z) {
1972 if (e > 0xffffffff || e < 1) {
1973 return BigInteger.ONE;
1977 var g = z.convert(this);
1978 var i = nbits(e) - 1;
1982 if ((e & (1 << i)) > 0) {
1993 // BigInteger.prototype.chunkSize = bnpChunkSize;
1994 // (protected) return x s.t. r^x < DV
1995 BigInteger.prototype.chunkSize = function (r) {
1996 return Math.floor(Math.LN2 * this.DB / Math.log(r));
1998 // BigInteger.prototype.toRadix = bnpToRadix;
1999 // (protected) convert to radix string
2000 BigInteger.prototype.toRadix = function (b) {
2004 if (this.signum() == 0 || b < 2 || b > 36) {
2007 var cs = this.chunkSize(b);
2008 var a = Math.pow(b, cs);
2013 this.divRemTo(d, y, z);
2014 while (y.signum() > 0) {
2015 r = (a + z.intValue()).toString(b).substr(1) + r;
2016 y.divRemTo(d, y, z);
2018 return z.intValue().toString(b) + r;
2020 // BigInteger.prototype.fromRadix = bnpFromRadix;
2021 // (protected) convert from radix string
2022 BigInteger.prototype.fromRadix = function (s, b) {
2027 var cs = this.chunkSize(b);
2028 var d = Math.pow(b, cs);
2032 for (var i = 0; i < s.length; ++i) {
2033 var x = intAt(s, i);
2035 if (s.charAt(i) == "-" && this.signum() == 0) {
2043 this.dAddOffset(w, 0);
2049 this.dMultiply(Math.pow(b, j));
2050 this.dAddOffset(w, 0);
2053 BigInteger.ZERO.subTo(this, this);
2056 // BigInteger.prototype.fromNumber = bnpFromNumber;
2057 // (protected) alternate constructor
2058 BigInteger.prototype.fromNumber = function (a, b, c) {
2059 if ("number" == typeof b) {
2060 // new BigInteger(int,int,RNG)
2065 this.fromNumber(a, c);
2066 if (!this.testBit(a - 1)) {
2068 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2070 if (this.isEven()) {
2071 this.dAddOffset(1, 0);
2073 while (!this.isProbablePrime(b)) {
2074 this.dAddOffset(2, 0);
2075 if (this.bitLength() > a) {
2076 this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
2082 // new BigInteger(int,RNG)
2085 x.length = (a >> 3) + 1;
2088 x[0] &= ((1 << t) - 1);
2093 this.fromString(x, 256);
2096 // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
2097 // (protected) r = this op a (bitwise)
2098 BigInteger.prototype.bitwiseTo = function (a, op, r) {
2101 var m = Math.min(a.t, this.t);
2102 for (i = 0; i < m; ++i) {
2103 r[i] = op(this[i], a[i]);
2107 for (i = m; i < this.t; ++i) {
2108 r[i] = op(this[i], f);
2113 f = this.s & this.DM;
2114 for (i = m; i < a.t; ++i) {
2119 r.s = op(this.s, a.s);
2122 // BigInteger.prototype.changeBit = bnpChangeBit;
2123 // (protected) this op (1<<n)
2124 BigInteger.prototype.changeBit = function (n, op) {
2125 var r = BigInteger.ONE.shiftLeft(n);
2126 this.bitwiseTo(r, op, r);
2129 // BigInteger.prototype.addTo = bnpAddTo;
2130 // (protected) r = this + a
2131 BigInteger.prototype.addTo = function (a, r) {
2134 var m = Math.min(a.t, this.t);
2136 c += this[i] + a[i];
2137 r[i++] = c & this.DM;
2142 while (i < this.t) {
2144 r[i++] = c & this.DM;
2153 r[i++] = c & this.DM;
2158 r.s = (c < 0) ? -1 : 0;
2163 r[i++] = this.DV + c;
2168 // BigInteger.prototype.dMultiply = bnpDMultiply;
2169 // (protected) this *= n, this >= 0, 1 < n < DV
2170 BigInteger.prototype.dMultiply = function (n) {
2171 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
2175 // BigInteger.prototype.dAddOffset = bnpDAddOffset;
2176 // (protected) this += n << w words, this >= 0
2177 BigInteger.prototype.dAddOffset = function (n, w) {
2181 while (this.t <= w) {
2185 while (this[w] >= this.DV) {
2187 if (++w >= this.t) {
2193 // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
2194 // (protected) r = lower n words of "this * a", a.t <= n
2195 // "this" should be the larger one if appropriate.
2196 BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
2197 var i = Math.min(this.t + a.t, n);
2198 r.s = 0; // assumes a,this >= 0
2203 for (var j = r.t - this.t; i < j; ++i) {
2204 r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
2206 for (var j = Math.min(a.t, n); i < j; ++i) {
2207 this.am(0, a[i], r, i, 0, n - i);
2211 // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
2212 // (protected) r = "this * a" without lower n words, n > 0
2213 // "this" should be the larger one if appropriate.
2214 BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
2216 var i = r.t = this.t + a.t - n;
2217 r.s = 0; // assumes a,this >= 0
2221 for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
2222 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
2227 // BigInteger.prototype.modInt = bnpModInt;
2228 // (protected) this % n, n < 2^26
2229 BigInteger.prototype.modInt = function (n) {
2233 var d = this.DV % n;
2234 var r = (this.s < 0) ? n - 1 : 0;
2240 for (var i = this.t - 1; i >= 0; --i) {
2241 r = (d * r + this[i]) % n;
2247 // BigInteger.prototype.millerRabin = bnpMillerRabin;
2248 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
2249 BigInteger.prototype.millerRabin = function (t) {
2250 var n1 = this.subtract(BigInteger.ONE);
2251 var k = n1.getLowestSetBit();
2255 var r = n1.shiftRight(k);
2257 if (t > lowprimes.length) {
2258 t = lowprimes.length;
2261 for (var i = 0; i < t; ++i) {
2262 // Pick bases at random, instead of starting at 2
2263 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
2264 var y = a.modPow(r, this);
2265 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
2267 while (j++ < k && y.compareTo(n1) != 0) {
2268 y = y.modPowInt(2, this);
2269 if (y.compareTo(BigInteger.ONE) == 0) {
2273 if (y.compareTo(n1) != 0) {
2280 // BigInteger.prototype.square = bnSquare;
2282 BigInteger.prototype.square = function () {
2288 // Public API method
2289 BigInteger.prototype.gcda = function (a, callback) {
2290 var x = (this.s < 0) ? this.negate() : this.clone();
2291 var y = (a.s < 0) ? a.negate() : a.clone();
2292 if (x.compareTo(y) < 0) {
2297 var i = x.getLowestSetBit();
2298 var g = y.getLowestSetBit();
2310 // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
2311 var gcda1 = function () {
2312 if ((i = x.getLowestSetBit()) > 0) {
2315 if ((i = y.getLowestSetBit()) > 0) {
2318 if (x.compareTo(y) >= 0) {
2326 if (!(x.signum() > 0)) {
2330 setTimeout(function () { callback(y); }, 0); // escape
2333 setTimeout(gcda1, 0);
2336 setTimeout(gcda1, 10);
2338 // (protected) alternate constructor
2339 BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
2340 if ("number" == typeof b) {
2345 this.fromNumber(a, c);
2346 if (!this.testBit(a - 1)) {
2347 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2349 if (this.isEven()) {
2350 this.dAddOffset(1, 0);
2353 var bnpfn1_1 = function () {
2354 bnp_1.dAddOffset(2, 0);
2355 if (bnp_1.bitLength() > a) {
2356 bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
2358 if (bnp_1.isProbablePrime(b)) {
2359 setTimeout(function () { callback(); }, 0); // escape
2362 setTimeout(bnpfn1_1, 0);
2365 setTimeout(bnpfn1_1, 0);
2371 x.length = (a >> 3) + 1;
2374 x[0] &= ((1 << t) - 1);
2379 this.fromString(x, 256);
2386 var NullExp = /** @class */ (function () {
2387 function NullExp() {
2389 // NullExp.prototype.convert = nNop;
2390 NullExp.prototype.convert = function (x) {
2393 // NullExp.prototype.revert = nNop;
2394 NullExp.prototype.revert = function (x) {
2397 // NullExp.prototype.mulTo = nMulTo;
2398 NullExp.prototype.mulTo = function (x, y, r) {
2401 // NullExp.prototype.sqrTo = nSqrTo;
2402 NullExp.prototype.sqrTo = function (x, r) {
2407 // Modular reduction using "classic" algorithm
2408 var Classic = /** @class */ (function () {
2409 function Classic(m) {
2412 // Classic.prototype.convert = cConvert;
2413 Classic.prototype.convert = function (x) {
2414 if (x.s < 0 || x.compareTo(this.m) >= 0) {
2415 return x.mod(this.m);
2421 // Classic.prototype.revert = cRevert;
2422 Classic.prototype.revert = function (x) {
2425 // Classic.prototype.reduce = cReduce;
2426 Classic.prototype.reduce = function (x) {
2427 x.divRemTo(this.m, null, x);
2429 // Classic.prototype.mulTo = cMulTo;
2430 Classic.prototype.mulTo = function (x, y, r) {
2434 // Classic.prototype.sqrTo = cSqrTo;
2435 Classic.prototype.sqrTo = function (x, r) {
2442 //#region Montgomery
2443 // Montgomery reduction
2444 var Montgomery = /** @class */ (function () {
2445 function Montgomery(m) {
2447 this.mp = m.invDigit();
2448 this.mpl = this.mp & 0x7fff;
2449 this.mph = this.mp >> 15;
2450 this.um = (1 << (m.DB - 15)) - 1;
2453 // Montgomery.prototype.convert = montConvert;
2455 Montgomery.prototype.convert = function (x) {
2457 x.abs().dlShiftTo(this.m.t, r);
2458 r.divRemTo(this.m, null, r);
2459 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
2464 // Montgomery.prototype.revert = montRevert;
2466 Montgomery.prototype.revert = function (x) {
2472 // Montgomery.prototype.reduce = montReduce;
2473 // x = x/R mod m (HAC 14.32)
2474 Montgomery.prototype.reduce = function (x) {
2475 while (x.t <= this.mt2) {
2476 // pad x so am has enough room later
2479 for (var i = 0; i < this.m.t; ++i) {
2480 // faster way of calculating u0 = x[i]*mp mod DV
2481 var j = x[i] & 0x7fff;
2482 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
2483 // use am to combine the multiply-shift-add into one call
2485 x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
2487 while (x[j] >= x.DV) {
2493 x.drShiftTo(this.m.t, x);
2494 if (x.compareTo(this.m) >= 0) {
2498 // Montgomery.prototype.mulTo = montMulTo;
2499 // r = "xy/R mod m"; x,y != r
2500 Montgomery.prototype.mulTo = function (x, y, r) {
2504 // Montgomery.prototype.sqrTo = montSqrTo;
2505 // r = "x^2/R mod m"; x != r
2506 Montgomery.prototype.sqrTo = function (x, r) {
2512 //#endregion Montgomery
2514 // Barrett modular reduction
2515 var Barrett = /** @class */ (function () {
2516 function Barrett(m) {
2521 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
2522 this.mu = this.r2.divide(m);
2524 // Barrett.prototype.convert = barrettConvert;
2525 Barrett.prototype.convert = function (x) {
2526 if (x.s < 0 || x.t > 2 * this.m.t) {
2527 return x.mod(this.m);
2529 else if (x.compareTo(this.m) < 0) {
2539 // Barrett.prototype.revert = barrettRevert;
2540 Barrett.prototype.revert = function (x) {
2543 // Barrett.prototype.reduce = barrettReduce;
2544 // x = x mod m (HAC 14.42)
2545 Barrett.prototype.reduce = function (x) {
2546 x.drShiftTo(this.m.t - 1, this.r2);
2547 if (x.t > this.m.t + 1) {
2551 this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
2552 this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
2553 while (x.compareTo(this.r2) < 0) {
2554 x.dAddOffset(1, this.m.t + 1);
2556 x.subTo(this.r2, x);
2557 while (x.compareTo(this.m) >= 0) {
2561 // Barrett.prototype.mulTo = barrettMulTo;
2562 // r = x*y mod m; x,y != r
2563 Barrett.prototype.mulTo = function (x, y, r) {
2567 // Barrett.prototype.sqrTo = barrettSqrTo;
2568 // r = x^2 mod m; x != r
2569 Barrett.prototype.sqrTo = function (x, r) {
2576 //#endregion REDUCERS
2577 // return new, unset BigInteger
2578 function nbi() { return new BigInteger(null); }
2579 function parseBigInt(str, r) {
2580 return new BigInteger(str, r);
2582 // am: Compute w_j += (x*this_i), propagate carries,
2583 // c is initial carry, returns final carry.
2584 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
2585 // We need to select the fastest one that works in this environment.
2586 // am1: use a single mult and divide to get the high bits,
2587 // max digit bits should be 26 because
2588 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
2589 function am1(i, x, w, j, c, n) {
2591 var v = x * this[i++] + w[j] + c;
2592 c = Math.floor(v / 0x4000000);
2593 w[j++] = v & 0x3ffffff;
2597 // am2 avoids a big mult-and-extract completely.
2598 // Max digit bits should be <= 30 because we do bitwise ops
2599 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
2600 function am2(i, x, w, j, c, n) {
2601 var xl = x & 0x7fff;
2604 var l = this[i] & 0x7fff;
2605 var h = this[i++] >> 15;
2606 var m = xh * l + h * xl;
2607 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
2608 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
2609 w[j++] = l & 0x3fffffff;
2613 // Alternately, set max digit bits to 28 since some
2614 // browsers slow down when dealing with 32-bit numbers.
2615 function am3(i, x, w, j, c, n) {
2616 var xl = x & 0x3fff;
2619 var l = this[i] & 0x3fff;
2620 var h = this[i++] >> 14;
2621 var m = xh * l + h * xl;
2622 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
2623 c = (l >> 28) + (m >> 14) + xh * h;
2624 w[j++] = l & 0xfffffff;
2628 // if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
2629 // BigInteger.prototype.am = am2;
2632 // else if (j_lm && (navigator.appName != "Netscape")) {
2633 // BigInteger.prototype.am = am1;
2636 // else { // Mozilla/Netscape seems to prefer am3
2637 // BigInteger.prototype.am = am3;
2640 BigInteger.prototype.am = am1;
2643 BigInteger.prototype.DB = dbits;
2644 BigInteger.prototype.DM = ((1 << dbits) - 1);
2645 BigInteger.prototype.DV = (1 << dbits);
2647 BigInteger.prototype.FV = Math.pow(2, BI_FP);
2648 BigInteger.prototype.F1 = BI_FP - dbits;
2649 BigInteger.prototype.F2 = 2 * dbits - BI_FP;
2650 // Digit conversions
2654 rr = "0".charCodeAt(0);
2655 for (vv = 0; vv <= 9; ++vv) {
2658 rr = "a".charCodeAt(0);
2659 for (vv = 10; vv < 36; ++vv) {
2662 rr = "A".charCodeAt(0);
2663 for (vv = 10; vv < 36; ++vv) {
2666 function intAt(s, i) {
2667 var c = BI_RC[s.charCodeAt(i)];
2668 return (c == null) ? -1 : c;
2670 // return bigint initialized to value
2676 // returns bit length of the integer x
2680 if ((t = x >>> 16) != 0) {
2684 if ((t = x >> 8) != 0) {
2688 if ((t = x >> 4) != 0) {
2692 if ((t = x >> 2) != 0) {
2696 if ((t = x >> 1) != 0) {
2703 BigInteger.ZERO = nbv(0);
2704 BigInteger.ONE = nbv(1);
2706 // prng4.js - uses Arcfour as a PRNG
2707 var Arcfour = /** @class */ (function () {
2708 function Arcfour() {
2713 // Arcfour.prototype.init = ARC4init;
2714 // Initialize arcfour context from key, an array of ints, each from [0..255]
2715 Arcfour.prototype.init = function (key) {
2719 for (i = 0; i < 256; ++i) {
2723 for (i = 0; i < 256; ++i) {
2724 j = (j + this.S[i] + key[i % key.length]) & 255;
2726 this.S[i] = this.S[j];
2732 // Arcfour.prototype.next = ARC4next;
2733 Arcfour.prototype.next = function () {
2735 this.i = (this.i + 1) & 255;
2736 this.j = (this.j + this.S[this.i]) & 255;
2738 this.S[this.i] = this.S[this.j];
2740 return this.S[(t + this.S[this.i]) & 255];
2744 // Plug in your RNG constructor here
2745 function prng_newstate() {
2746 return new Arcfour();
2748 // Pool size must be a multiple of 4 and greater than 32.
2749 // An array of bytes the size of the pool will be passed to init()
2750 var rng_psize = 256;
2752 // Random number generator - requires a PRNG backend, e.g. prng4.js
2754 var rng_pool = null;
2756 // Initialize the pool with junk if needed.
2757 if (rng_pool == null) {
2761 if (window.crypto && window.crypto.getRandomValues) {
2762 // Extract entropy (2048 bits) from RNG if available
2763 var z = new Uint32Array(256);
2764 window.crypto.getRandomValues(z);
2765 for (t = 0; t < z.length; ++t) {
2766 rng_pool[rng_pptr++] = z[t] & 255;
2769 // Use mouse events for entropy, if we do not have enough entropy by the time
2770 // we need it, entropy will be generated by Math.random.
2771 var onMouseMoveListener_1 = function (ev) {
2772 this.count = this.count || 0;
2773 if (this.count >= 256 || rng_pptr >= rng_psize) {
2774 if (window.removeEventListener) {
2775 window.removeEventListener("mousemove", onMouseMoveListener_1, false);
2777 else if (window.detachEvent) {
2778 window.detachEvent("onmousemove", onMouseMoveListener_1);
2783 var mouseCoordinates = ev.x + ev.y;
2784 rng_pool[rng_pptr++] = mouseCoordinates & 255;
2788 // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
2791 if (window.addEventListener) {
2792 window.addEventListener("mousemove", onMouseMoveListener_1, false);
2794 else if (window.attachEvent) {
2795 window.attachEvent("onmousemove", onMouseMoveListener_1);
2798 function rng_get_byte() {
2799 if (rng_state == null) {
2800 rng_state = prng_newstate();
2801 // At this point, we may not have collected enough entropy. If not, fall back to Math.random
2802 while (rng_pptr < rng_psize) {
2803 var random = Math.floor(65536 * Math.random());
2804 rng_pool[rng_pptr++] = random & 255;
2806 rng_state.init(rng_pool);
2807 for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
2808 rng_pool[rng_pptr] = 0;
2812 // TODO: allow reseeding after first request
2813 return rng_state.next();
2815 var SecureRandom = /** @class */ (function () {
2816 function SecureRandom() {
2818 SecureRandom.prototype.nextBytes = function (ba) {
2819 for (var i = 0; i < ba.length; ++i) {
2820 ba[i] = rng_get_byte();
2823 return SecureRandom;
2826 // Depends on jsbn.js and rng.js
2827 // function linebrk(s,n) {
2830 // while(i + n < s.length) {
2831 // ret += s.substring(i,i+n) + "\n";
2834 // return ret + s.substring(i,s.length);
2836 // function byte2Hex(b) {
2838 // return "0" + b.toString(16);
2840 // return b.toString(16);
2842 function pkcs1pad1(s, n) {
2843 if (n < s.length + 22) {
2844 console.error("Message too long for RSA");
2847 var len = n - s.length - 6;
2849 for (var f = 0; f < len; f += 2) {
2852 var m = "0001" + filler + "00" + s;
2853 return parseBigInt(m, 16);
2855 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
2856 function pkcs1pad2(s, n) {
2857 if (n < s.length + 11) { // TODO: fix for utf-8
2858 console.error("Message too long for RSA");
2862 var i = s.length - 1;
2863 while (i >= 0 && n > 0) {
2864 var c = s.charCodeAt(i--);
2865 if (c < 128) { // encode using utf-8
2868 else if ((c > 127) && (c < 2048)) {
2869 ba[--n] = (c & 63) | 128;
2870 ba[--n] = (c >> 6) | 192;
2873 ba[--n] = (c & 63) | 128;
2874 ba[--n] = ((c >> 6) & 63) | 128;
2875 ba[--n] = (c >> 12) | 224;
2879 var rng = new SecureRandom();
2881 while (n > 2) { // random non-zero pad
2890 return new BigInteger(ba);
2892 // "empty" RSA key constructor
2893 var RSAKey = /** @class */ (function () {
2906 // RSAKey.prototype.doPublic = RSADoPublic;
2907 // Perform raw public operation on "x": return x^e (mod n)
2908 RSAKey.prototype.doPublic = function (x) {
2909 return x.modPowInt(this.e, this.n);
2911 // RSAKey.prototype.doPrivate = RSADoPrivate;
2912 // Perform raw private operation on "x": return x^d (mod n)
2913 RSAKey.prototype.doPrivate = function (x) {
2914 if (this.p == null || this.q == null) {
2915 return x.modPow(this.d, this.n);
2917 // TODO: re-calculate any missing CRT params
2918 var xp = x.mod(this.p).modPow(this.dmp1, this.p);
2919 var xq = x.mod(this.q).modPow(this.dmq1, this.q);
2920 while (xp.compareTo(xq) < 0) {
2921 xp = xp.add(this.p);
2923 return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
2925 //#endregion PROTECTED
2927 // RSAKey.prototype.setPublic = RSASetPublic;
2928 // Set the public key fields N and e from hex strings
2929 RSAKey.prototype.setPublic = function (N, E) {
2930 if (N != null && E != null && N.length > 0 && E.length > 0) {
2931 this.n = parseBigInt(N, 16);
2932 this.e = parseInt(E, 16);
2935 console.error("Invalid RSA public key");
2938 // RSAKey.prototype.encrypt = RSAEncrypt;
2939 // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
2940 RSAKey.prototype.encrypt = function (text) {
2941 var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
2945 var c = this.doPublic(m);
2949 var h = c.toString(16);
2950 if ((h.length & 1) == 0) {
2957 // RSAKey.prototype.setPrivate = RSASetPrivate;
2958 // Set the private key fields N, e, and d from hex strings
2959 RSAKey.prototype.setPrivate = function (N, E, D) {
2960 if (N != null && E != null && N.length > 0 && E.length > 0) {
2961 this.n = parseBigInt(N, 16);
2962 this.e = parseInt(E, 16);
2963 this.d = parseBigInt(D, 16);
2966 console.error("Invalid RSA private key");
2969 // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
2970 // Set the private key fields N, e, d and CRT params from hex strings
2971 RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
2972 if (N != null && E != null && N.length > 0 && E.length > 0) {
2973 this.n = parseBigInt(N, 16);
2974 this.e = parseInt(E, 16);
2975 this.d = parseBigInt(D, 16);
2976 this.p = parseBigInt(P, 16);
2977 this.q = parseBigInt(Q, 16);
2978 this.dmp1 = parseBigInt(DP, 16);
2979 this.dmq1 = parseBigInt(DQ, 16);
2980 this.coeff = parseBigInt(C, 16);
2983 console.error("Invalid RSA private key");
2986 // RSAKey.prototype.generate = RSAGenerate;
2987 // Generate a new random private key B bits long, using public expt E
2988 RSAKey.prototype.generate = function (B, E) {
2989 var rng = new SecureRandom();
2991 this.e = parseInt(E, 16);
2992 var ee = new BigInteger(E, 16);
2995 this.p = new BigInteger(B - qs, 1, rng);
2996 if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
3001 this.q = new BigInteger(qs, 1, rng);
3002 if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
3006 if (this.p.compareTo(this.q) <= 0) {
3011 var p1 = this.p.subtract(BigInteger.ONE);
3012 var q1 = this.q.subtract(BigInteger.ONE);
3013 var phi = p1.multiply(q1);
3014 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3015 this.n = this.p.multiply(this.q);
3016 this.d = ee.modInverse(phi);
3017 this.dmp1 = this.d.mod(p1);
3018 this.dmq1 = this.d.mod(q1);
3019 this.coeff = this.q.modInverse(this.p);
3024 // RSAKey.prototype.decrypt = RSADecrypt;
3025 // Return the PKCS#1 RSA decryption of "ctext".
3026 // "ctext" is an even-length hex string and the output is a plain string.
3027 RSAKey.prototype.decrypt = function (ctext) {
3028 var c = parseBigInt(ctext, 16);
3029 var m = this.doPrivate(c);
3033 return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
3035 // Generate a new random private key B bits long, using public expt E
3036 RSAKey.prototype.generateAsync = function (B, E, callback) {
3037 var rng = new SecureRandom();
3039 this.e = parseInt(E, 16);
3040 var ee = new BigInteger(E, 16);
3042 // These functions have non-descript names because they were originally for(;;) loops.
3043 // I don't know about cryptography to give them better names than loop1-4.
3044 var loop1 = function () {
3045 var loop4 = function () {
3046 if (rsa.p.compareTo(rsa.q) <= 0) {
3051 var p1 = rsa.p.subtract(BigInteger.ONE);
3052 var q1 = rsa.q.subtract(BigInteger.ONE);
3053 var phi = p1.multiply(q1);
3054 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3055 rsa.n = rsa.p.multiply(rsa.q);
3056 rsa.d = ee.modInverse(phi);
3057 rsa.dmp1 = rsa.d.mod(p1);
3058 rsa.dmq1 = rsa.d.mod(q1);
3059 rsa.coeff = rsa.q.modInverse(rsa.p);
3060 setTimeout(function () { callback(); }, 0); // escape
3063 setTimeout(loop1, 0);
3066 var loop3 = function () {
3068 rsa.q.fromNumberAsync(qs, 1, rng, function () {
3069 rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
3070 if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
3071 setTimeout(loop4, 0);
3074 setTimeout(loop3, 0);
3079 var loop2 = function () {
3081 rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
3082 rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
3083 if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
3084 setTimeout(loop3, 0);
3087 setTimeout(loop2, 0);
3092 setTimeout(loop2, 0);
3094 setTimeout(loop1, 0);
3096 RSAKey.prototype.sign = function (text, digestMethod, digestName) {
3097 var header = getDigestHeader(digestName);
3098 var digest = header + digestMethod(text).toString();
3099 var m = pkcs1pad1(digest, this.n.bitLength() / 4);
3103 var c = this.doPrivate(m);
3107 var h = c.toString(16);
3108 if ((h.length & 1) == 0) {
3115 RSAKey.prototype.verify = function (text, signature, digestMethod) {
3116 var c = parseBigInt(signature, 16);
3117 var m = this.doPublic(c);
3121 var unpadded = m.toString(16).replace(/^1f+00/, "");
3122 var digest = removeDigestHeader(unpadded);
3123 return digest == digestMethod(text).toString();
3127 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
3128 function pkcs1unpad2(d, n) {
3129 var b = d.toByteArray();
3131 while (i < b.length && b[i] == 0) {
3134 if (b.length - i != n - 1 || b[i] != 2) {
3139 if (++i >= b.length) {
3144 while (++i < b.length) {
3146 if (c < 128) { // utf-8 decode
3147 ret += String.fromCharCode(c);
3149 else if ((c > 191) && (c < 224)) {
3150 ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
3154 ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
3160 // https://tools.ietf.org/html/rfc3447#page-43
3161 var DIGEST_HEADERS = {
3162 md2: "3020300c06082a864886f70d020205000410",
3163 md5: "3020300c06082a864886f70d020505000410",
3164 sha1: "3021300906052b0e03021a05000414",
3165 sha224: "302d300d06096086480165030402040500041c",
3166 sha256: "3031300d060960864801650304020105000420",
3167 sha384: "3041300d060960864801650304020205000430",
3168 sha512: "3051300d060960864801650304020305000440",
3169 ripemd160: "3021300906052b2403020105000414",
3171 function getDigestHeader(name) {
3172 return DIGEST_HEADERS[name] || "";
3174 function removeDigestHeader(str) {
3175 for (var name_1 in DIGEST_HEADERS) {
3176 if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
3177 var header = DIGEST_HEADERS[name_1];
3178 var len = header.length;
3179 if (str.substr(0, len) == header) {
3180 return str.substr(len);
3186 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
3187 // function RSAEncryptB64(text) {
3188 // var h = this.encrypt(text);
3189 // if(h) return hex2b64(h); else return null;
3192 // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
3195 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3196 Code licensed under the BSD License:
3197 http://developer.yahoo.com/yui/license.html
3203 * Utility to set up the prototype, constructor and superclass properties to
3204 * support an inheritance strategy that can chain constructors and methods.
3205 * Static members will not be inherited.
3209 * @param {Function} subc the object to modify
3210 * @param {Function} superc the object to inherit
3211 * @param {Object} overrides additional properties/methods to add to the
3212 * subclass prototype. These will override the
3213 * matching items obtained from the superclass
3216 extend: function(subc, superc, overrides) {
3217 if (! superc || ! subc) {
3218 throw new Error("YAHOO.lang.extend failed, please check that " +
3219 "all dependencies are included.");
3222 var F = function() {};
3223 F.prototype = superc.prototype;
3224 subc.prototype = new F();
3225 subc.prototype.constructor = subc;
3226 subc.superclass = superc.prototype;
3228 if (superc.prototype.constructor == Object.prototype.constructor) {
3229 superc.prototype.constructor = superc;
3234 for (i in overrides) {
3235 subc.prototype[i] = overrides[i];
3239 * IE will not enumerate native functions in a derived object even if the
3240 * function was overridden. This is a workaround for specific functions
3241 * we care about on the Object prototype.
3242 * @property _IEEnumFix
3243 * @param {Function} r the object to receive the augmentation
3244 * @param {Function} s the object that supplies the properties to augment
3248 var _IEEnumFix = function() {},
3249 ADD = ["toString", "valueOf"];
3251 if (/MSIE/.test(navigator.userAgent)) {
3252 _IEEnumFix = function(r, s) {
3253 for (i = 0; i < ADD.length; i = i + 1) {
3254 var fname = ADD[i], f = s[fname];
3255 if (typeof f === 'function' && f != Object.prototype[fname]) {
3261 } catch (ex) {} _IEEnumFix(subc.prototype, overrides);
3266 /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
3272 * @author Kenji Urushima kenji.urushima@gmail.com
3273 * @version asn1 1.0.13 (2017-Jun-02)
3274 * @since jsrsasign 2.1
3275 * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
3279 * kjur's class library name space
3281 * This name space provides following name spaces:
3283 * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
3284 * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
3285 * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
3286 * class and utilities</li>
3289 * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
3291 * @namespace kjur's class library name space
3296 * kjur's ASN.1 class library name space
3298 * This is ITU-T X.690 ASN.1 DER encoder class library and
3299 * class structure and methods is very similar to
3300 * org.bouncycastle.asn1 package of
3301 * well known BouncyCaslte Cryptography Library.
3302 * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
3303 * Here are ASN.1 DER primitive classes.
3305 * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
3306 * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
3307 * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
3308 * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
3309 * <li>0x05 {@link KJUR.asn1.DERNull}</li>
3310 * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
3311 * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
3312 * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
3313 * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
3314 * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
3315 * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
3316 * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
3317 * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
3318 * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
3319 * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
3320 * <li>0x31 {@link KJUR.asn1.DERSet}</li>
3322 * <h4>OTHER ASN.1 CLASSES</h4>
3324 * <li>{@link KJUR.asn1.ASN1Object}</li>
3325 * <li>{@link KJUR.asn1.DERAbstractString}</li>
3326 * <li>{@link KJUR.asn1.DERAbstractTime}</li>
3327 * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
3328 * <li>{@link KJUR.asn1.DERTaggedObject}</li>
3330 * <h4>SUB NAME SPACES</h4>
3332 * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
3333 * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
3334 * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
3335 * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
3336 * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
3339 * NOTE: Please ignore method summary and document of this namespace.
3340 * This caused by a bug of jsdoc2.
3344 if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
3347 * ASN1 utilities class
3348 * @name KJUR.asn1.ASN1Util
3349 * @class ASN1 utilities class
3352 KJUR.asn1.ASN1Util = new function() {
3353 this.integerToByteHex = function(i) {
3354 var h = i.toString(16);
3355 if ((h.length % 2) == 1) h = '0' + h;
3358 this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
3359 var h = bigIntegerValue.toString(16);
3360 if (h.substr(0, 1) != '-') {
3361 if (h.length % 2 == 1) {
3364 if (! h.match(/^[0-7]/)) {
3369 var hPos = h.substr(1);
3370 var xorLen = hPos.length;
3371 if (xorLen % 2 == 1) {
3374 if (! h.match(/^[0-7]/)) {
3379 for (var i = 0; i < xorLen; i++) {
3382 var biMask = new BigInteger(hMask, 16);
3383 var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
3384 h = biNeg.toString(16).replace(/^-/, '');
3389 * get PEM string from hexadecimal data and header string
3390 * @name getPEMStringFromHex
3391 * @memberOf KJUR.asn1.ASN1Util
3393 * @param {String} dataHex hexadecimal string of PEM body
3394 * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
3395 * @return {String} PEM formatted string of input data
3397 * This method converts a hexadecimal string to a PEM string with
3398 * a specified header. Its line break will be CRLF("\r\n").
3400 * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
3401 * // value of pem will be:
3402 * -----BEGIN PRIVATE KEY-----
3404 * -----END PRIVATE KEY-----
3406 this.getPEMStringFromHex = function(dataHex, pemHeader) {
3407 return hextopem(dataHex, pemHeader);
3411 * generate ASN1Object specifed by JSON parameters
3413 * @memberOf KJUR.asn1.ASN1Util
3415 * @param {Array} param JSON parameter to generate ASN1Object
3416 * @return {KJUR.asn1.ASN1Object} generated object
3419 * generate any ASN1Object specified by JSON param
3420 * including ASN.1 primitive or structured.
3421 * Generally 'param' can be described as follows:
3423 * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
3425 * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
3427 * <li>'bool' - DERBoolean</li>
3428 * <li>'int' - DERInteger</li>
3429 * <li>'bitstr' - DERBitString</li>
3430 * <li>'octstr' - DEROctetString</li>
3431 * <li>'null' - DERNull</li>
3432 * <li>'oid' - DERObjectIdentifier</li>
3433 * <li>'enum' - DEREnumerated</li>
3434 * <li>'utf8str' - DERUTF8String</li>
3435 * <li>'numstr' - DERNumericString</li>
3436 * <li>'prnstr' - DERPrintableString</li>
3437 * <li>'telstr' - DERTeletexString</li>
3438 * <li>'ia5str' - DERIA5String</li>
3439 * <li>'utctime' - DERUTCTime</li>
3440 * <li>'gentime' - DERGeneralizedTime</li>
3441 * <li>'seq' - DERSequence</li>
3442 * <li>'set' - DERSet</li>
3443 * <li>'tag' - DERTaggedObject</li>
3446 * newObject({'prnstr': 'aaa'});
3447 * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
3448 * // ASN.1 Tagged Object
3449 * newObject({'tag': {'tag': 'a1',
3451 * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
3452 * // more simple representation of ASN.1 Tagged Object
3453 * newObject({'tag': ['a1',
3457 * {'prnstr': 'aaa'}]}
3460 this.newObject = function(param) {
3462 _KJUR_asn1 = _KJUR.asn1,
3463 _DERBoolean = _KJUR_asn1.DERBoolean,
3464 _DERInteger = _KJUR_asn1.DERInteger,
3465 _DERBitString = _KJUR_asn1.DERBitString,
3466 _DEROctetString = _KJUR_asn1.DEROctetString,
3467 _DERNull = _KJUR_asn1.DERNull,
3468 _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
3469 _DEREnumerated = _KJUR_asn1.DEREnumerated,
3470 _DERUTF8String = _KJUR_asn1.DERUTF8String,
3471 _DERNumericString = _KJUR_asn1.DERNumericString,
3472 _DERPrintableString = _KJUR_asn1.DERPrintableString,
3473 _DERTeletexString = _KJUR_asn1.DERTeletexString,
3474 _DERIA5String = _KJUR_asn1.DERIA5String,
3475 _DERUTCTime = _KJUR_asn1.DERUTCTime,
3476 _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
3477 _DERSequence = _KJUR_asn1.DERSequence,
3478 _DERSet = _KJUR_asn1.DERSet,
3479 _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
3480 _newObject = _KJUR_asn1.ASN1Util.newObject;
3482 var keys = Object.keys(param);
3483 if (keys.length != 1)
3484 throw "key of param shall be only one.";
3487 if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
3488 throw "undefined key: " + key;
3490 if (key == "bool") return new _DERBoolean(param[key]);
3491 if (key == "int") return new _DERInteger(param[key]);
3492 if (key == "bitstr") return new _DERBitString(param[key]);
3493 if (key == "octstr") return new _DEROctetString(param[key]);
3494 if (key == "null") return new _DERNull(param[key]);
3495 if (key == "oid") return new _DERObjectIdentifier(param[key]);
3496 if (key == "enum") return new _DEREnumerated(param[key]);
3497 if (key == "utf8str") return new _DERUTF8String(param[key]);
3498 if (key == "numstr") return new _DERNumericString(param[key]);
3499 if (key == "prnstr") return new _DERPrintableString(param[key]);
3500 if (key == "telstr") return new _DERTeletexString(param[key]);
3501 if (key == "ia5str") return new _DERIA5String(param[key]);
3502 if (key == "utctime") return new _DERUTCTime(param[key]);
3503 if (key == "gentime") return new _DERGeneralizedTime(param[key]);
3506 var paramList = param[key];
3508 for (var i = 0; i < paramList.length; i++) {
3509 var asn1Obj = _newObject(paramList[i]);
3512 return new _DERSequence({'array': a});
3516 var paramList = param[key];
3518 for (var i = 0; i < paramList.length; i++) {
3519 var asn1Obj = _newObject(paramList[i]);
3522 return new _DERSet({'array': a});
3526 var tagParam = param[key];
3527 if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
3528 tagParam.length == 3) {
3529 var obj = _newObject(tagParam[2]);
3530 return new _DERTaggedObject({tag: tagParam[0],
3531 explicit: tagParam[1],
3535 if (tagParam.explicit !== undefined)
3536 newParam.explicit = tagParam.explicit;
3537 if (tagParam.tag !== undefined)
3538 newParam.tag = tagParam.tag;
3539 if (tagParam.obj === undefined)
3540 throw "obj shall be specified for 'tag'.";
3541 newParam.obj = _newObject(tagParam.obj);
3542 return new _DERTaggedObject(newParam);
3548 * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
3549 * @name jsonToASN1HEX
3550 * @memberOf KJUR.asn1.ASN1Util
3552 * @param {Array} param JSON parameter to generate ASN1Object
3553 * @return hexadecimal string of ASN1Object
3556 * As for ASN.1 object representation of JSON object,
3557 * please see {@link newObject}.
3559 * jsonToASN1HEX({'prnstr': 'aaa'});
3561 this.jsonToASN1HEX = function(param) {
3562 var asn1Obj = this.newObject(param);
3563 return asn1Obj.getEncodedHex();
3568 * get dot noted oid number string from hexadecimal value of OID
3570 * @memberOf KJUR.asn1.ASN1Util
3572 * @param {String} hex hexadecimal value of object identifier
3573 * @return {String} dot noted string of object identifier
3574 * @since jsrsasign 4.8.3 asn1 1.0.7
3576 * This static method converts from hexadecimal string representation of
3577 * ASN.1 value of object identifier to oid number string.
3579 * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6"
3581 KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
3583 var i01 = parseInt(hex.substr(0, 2), 16);
3584 var i0 = Math.floor(i01 / 40);
3586 var s = i0 + "." + i1;
3589 for (var i = 2; i < hex.length; i += 2) {
3590 var value = parseInt(hex.substr(i, 2), 16);
3591 var bin = ("00000000" + value.toString(2)).slice(- 8);
3592 binbuf = binbuf + bin.substr(1, 7);
3593 if (bin.substr(0, 1) == "0") {
3594 var bi = new BigInteger(binbuf, 2);
3595 s = s + "." + bi.toString(10);
3603 * get hexadecimal value of object identifier from dot noted oid value
3605 * @memberOf KJUR.asn1.ASN1Util
3607 * @param {String} oidString dot noted string of object identifier
3608 * @return {String} hexadecimal value of object identifier
3609 * @since jsrsasign 4.8.3 asn1 1.0.7
3611 * This static method converts from object identifier value string.
3612 * to hexadecimal string representation of it.
3614 * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406"
3616 KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
3617 var itox = function(i) {
3618 var h = i.toString(16);
3619 if (h.length == 1) h = '0' + h;
3623 var roidtox = function(roid) {
3625 var bi = new BigInteger(roid, 10);
3626 var b = bi.toString(2);
3627 var padLen = 7 - b.length % 7;
3628 if (padLen == 7) padLen = 0;
3630 for (var i = 0; i < padLen; i++) bPad += '0';
3632 for (var i = 0; i < b.length - 1; i += 7) {
3633 var b8 = b.substr(i, 7);
3634 if (i != b.length - 7) b8 = '1' + b8;
3635 h += itox(parseInt(b8, 2));
3640 if (! oidString.match(/^[0-9.]+$/)) {
3641 throw "malformed oid string: " + oidString;
3644 var a = oidString.split('.');
3645 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
3648 for (var i = 0; i < a.length; i++) {
3655 // ********************************************************************
3656 // Abstract ASN.1 Classes
3657 // ********************************************************************
3659 // ********************************************************************
3662 * base class for ASN.1 DER encoder object
3663 * @name KJUR.asn1.ASN1Object
3664 * @class base class for ASN.1 DER encoder object
3665 * @property {Boolean} isModified flag whether internal data was changed
3666 * @property {String} hTLV hexadecimal string of ASN.1 TLV
3667 * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
3668 * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
3669 * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
3672 KJUR.asn1.ASN1Object = function() {
3676 * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
3677 * @name getLengthHexFromValue
3678 * @memberOf KJUR.asn1.ASN1Object#
3680 * @return {String} hexadecimal string of ASN.1 TLV length(L)
3682 this.getLengthHexFromValue = function() {
3683 if (typeof this.hV == "undefined" || this.hV == null) {
3684 throw "this.hV is null or undefined.";
3686 if (this.hV.length % 2 == 1) {
3687 throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
3689 var n = this.hV.length / 2;
3690 var hN = n.toString(16);
3691 if (hN.length % 2 == 1) {
3697 var hNlen = hN.length / 2;
3699 throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
3701 var head = 128 + hNlen;
3702 return head.toString(16) + hN;
3707 * get hexadecimal string of ASN.1 TLV bytes
3708 * @name getEncodedHex
3709 * @memberOf KJUR.asn1.ASN1Object#
3711 * @return {String} hexadecimal string of ASN.1 TLV
3713 this.getEncodedHex = function() {
3714 if (this.hTLV == null || this.isModified) {
3715 this.hV = this.getFreshValueHex();
3716 this.hL = this.getLengthHexFromValue();
3717 this.hTLV = this.hT + this.hL + this.hV;
3718 this.isModified = false;
3719 //alert("first time: " + this.hTLV);
3725 * get hexadecimal string of ASN.1 TLV value(V) bytes
3727 * @memberOf KJUR.asn1.ASN1Object#
3729 * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
3731 this.getValueHex = function() {
3732 this.getEncodedHex();
3736 this.getFreshValueHex = function() {
3741 // == BEGIN DERAbstractString ================================================
3743 * base class for ASN.1 DER string classes
3744 * @name KJUR.asn1.DERAbstractString
3745 * @class base class for ASN.1 DER string classes
3746 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
3747 * @property {String} s internal string of value
3748 * @extends KJUR.asn1.ASN1Object
3751 * As for argument 'params' for constructor, you can specify one of
3752 * following properties:
3754 * <li>str - specify initial ASN.1 value(V) by a string</li>
3755 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
3757 * NOTE: 'params' can be omitted.
3759 KJUR.asn1.DERAbstractString = function(params) {
3760 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3763 * get string value of this string object
3765 * @memberOf KJUR.asn1.DERAbstractString#
3767 * @return {String} string value of this string object
3769 this.getString = function() {
3774 * set value by a string
3776 * @memberOf KJUR.asn1.DERAbstractString#
3778 * @param {String} newS value by a string to set
3780 this.setString = function(newS) {
3782 this.isModified = true;
3784 this.hV = stohex(this.s);
3788 * set value by a hexadecimal string
3789 * @name setStringHex
3790 * @memberOf KJUR.asn1.DERAbstractString#
3792 * @param {String} newHexString value by a hexadecimal string to set
3794 this.setStringHex = function(newHexString) {
3796 this.isModified = true;
3798 this.hV = newHexString;
3801 this.getFreshValueHex = function() {
3805 if (typeof params != "undefined") {
3806 if (typeof params == "string") {
3807 this.setString(params);
3808 } else if (typeof params['str'] != "undefined") {
3809 this.setString(params['str']);
3810 } else if (typeof params['hex'] != "undefined") {
3811 this.setStringHex(params['hex']);
3815 YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
3816 // == END DERAbstractString ================================================
3818 // == BEGIN DERAbstractTime ==================================================
3820 * base class for ASN.1 DER Generalized/UTCTime class
3821 * @name KJUR.asn1.DERAbstractTime
3822 * @class base class for ASN.1 DER Generalized/UTCTime class
3823 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
3824 * @extends KJUR.asn1.ASN1Object
3826 * @see KJUR.asn1.ASN1Object - superclass
3828 KJUR.asn1.DERAbstractTime = function(params) {
3829 KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
3831 // --- PRIVATE METHODS --------------------
3832 this.localDateToUTC = function(d) {
3833 utc = d.getTime() + (d.getTimezoneOffset() * 60000);
3834 var utcDate = new Date(utc);
3839 * format date string by Data object
3841 * @memberOf KJUR.asn1.AbstractTime;
3842 * @param {Date} dateObject
3843 * @param {string} type 'utc' or 'gen'
3844 * @param {boolean} withMillis flag for with millisections or not
3846 * 'withMillis' flag is supported from asn1 1.0.6.
3848 this.formatDate = function(dateObject, type, withMillis) {
3849 var pad = this.zeroPadding;
3850 var d = this.localDateToUTC(dateObject);
3851 var year = String(d.getFullYear());
3852 if (type == 'utc') year = year.substr(2, 2);
3853 var month = pad(String(d.getMonth() + 1), 2);
3854 var day = pad(String(d.getDate()), 2);
3855 var hour = pad(String(d.getHours()), 2);
3856 var min = pad(String(d.getMinutes()), 2);
3857 var sec = pad(String(d.getSeconds()), 2);
3858 var s = year + month + day + hour + min + sec;
3859 if (withMillis === true) {
3860 var millis = d.getMilliseconds();
3862 var sMillis = pad(String(millis), 3);
3863 sMillis = sMillis.replace(/[0]+$/, "");
3864 s = s + "." + sMillis;
3870 this.zeroPadding = function(s, len) {
3871 if (s.length >= len) return s;
3872 return new Array(len - s.length + 1).join('0') + s;
3875 // --- PUBLIC METHODS --------------------
3877 * get string value of this string object
3879 * @memberOf KJUR.asn1.DERAbstractTime#
3881 * @return {String} string value of this time object
3883 this.getString = function() {
3888 * set value by a string
3890 * @memberOf KJUR.asn1.DERAbstractTime#
3892 * @param {String} newS value by a string to set such like "130430235959Z"
3894 this.setString = function(newS) {
3896 this.isModified = true;
3898 this.hV = stohex(newS);
3902 * set value by a Date object
3903 * @name setByDateValue
3904 * @memberOf KJUR.asn1.DERAbstractTime#
3906 * @param {Integer} year year of date (ex. 2013)
3907 * @param {Integer} month month of date between 1 and 12 (ex. 12)
3908 * @param {Integer} day day of month
3909 * @param {Integer} hour hours of date
3910 * @param {Integer} min minutes of date
3911 * @param {Integer} sec seconds of date
3913 this.setByDateValue = function(year, month, day, hour, min, sec) {
3914 var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
3915 this.setByDate(dateObject);
3918 this.getFreshValueHex = function() {
3922 YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
3923 // == END DERAbstractTime ==================================================
3925 // == BEGIN DERAbstractStructured ============================================
3927 * base class for ASN.1 DER structured class
3928 * @name KJUR.asn1.DERAbstractStructured
3929 * @class base class for ASN.1 DER structured class
3930 * @property {Array} asn1Array internal array of ASN1Object
3931 * @extends KJUR.asn1.ASN1Object
3933 * @see KJUR.asn1.ASN1Object - superclass
3935 KJUR.asn1.DERAbstractStructured = function(params) {
3936 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3939 * set value by array of ASN1Object
3940 * @name setByASN1ObjectArray
3941 * @memberOf KJUR.asn1.DERAbstractStructured#
3943 * @param {array} asn1ObjectArray array of ASN1Object to set
3945 this.setByASN1ObjectArray = function(asn1ObjectArray) {
3947 this.isModified = true;
3948 this.asn1Array = asn1ObjectArray;
3952 * append an ASN1Object to internal array
3953 * @name appendASN1Object
3954 * @memberOf KJUR.asn1.DERAbstractStructured#
3956 * @param {ASN1Object} asn1Object to add
3958 this.appendASN1Object = function(asn1Object) {
3960 this.isModified = true;
3961 this.asn1Array.push(asn1Object);
3964 this.asn1Array = new Array();
3965 if (typeof params != "undefined") {
3966 if (typeof params['array'] != "undefined") {
3967 this.asn1Array = params['array'];
3971 YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
3974 // ********************************************************************
3975 // ASN.1 Object Classes
3976 // ********************************************************************
3978 // ********************************************************************
3980 * class for ASN.1 DER Boolean
3981 * @name KJUR.asn1.DERBoolean
3982 * @class class for ASN.1 DER Boolean
3983 * @extends KJUR.asn1.ASN1Object
3985 * @see KJUR.asn1.ASN1Object - superclass
3987 KJUR.asn1.DERBoolean = function() {
3988 KJUR.asn1.DERBoolean.superclass.constructor.call(this);
3990 this.hTLV = "0101ff";
3992 YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
3994 // ********************************************************************
3996 * class for ASN.1 DER Integer
3997 * @name KJUR.asn1.DERInteger
3998 * @class class for ASN.1 DER Integer
3999 * @extends KJUR.asn1.ASN1Object
4002 * As for argument 'params' for constructor, you can specify one of
4003 * following properties:
4005 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4006 * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
4007 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4009 * NOTE: 'params' can be omitted.
4011 KJUR.asn1.DERInteger = function(params) {
4012 KJUR.asn1.DERInteger.superclass.constructor.call(this);
4016 * set value by Tom Wu's BigInteger object
4017 * @name setByBigInteger
4018 * @memberOf KJUR.asn1.DERInteger#
4020 * @param {BigInteger} bigIntegerValue to set
4022 this.setByBigInteger = function(bigIntegerValue) {
4024 this.isModified = true;
4025 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4029 * set value by integer value
4030 * @name setByInteger
4031 * @memberOf KJUR.asn1.DERInteger
4033 * @param {Integer} integer value to set
4035 this.setByInteger = function(intValue) {
4036 var bi = new BigInteger(String(intValue), 10);
4037 this.setByBigInteger(bi);
4041 * set value by integer value
4043 * @memberOf KJUR.asn1.DERInteger#
4045 * @param {String} hexadecimal string of integer value
4048 * NOTE: Value shall be represented by minimum octet length of
4049 * two's complement representation.
4051 * new KJUR.asn1.DERInteger(123);
4052 * new KJUR.asn1.DERInteger({'int': 123});
4053 * new KJUR.asn1.DERInteger({'hex': '1fad'});
4055 this.setValueHex = function(newHexString) {
4056 this.hV = newHexString;
4059 this.getFreshValueHex = function() {
4063 if (typeof params != "undefined") {
4064 if (typeof params['bigint'] != "undefined") {
4065 this.setByBigInteger(params['bigint']);
4066 } else if (typeof params['int'] != "undefined") {
4067 this.setByInteger(params['int']);
4068 } else if (typeof params == "number") {
4069 this.setByInteger(params);
4070 } else if (typeof params['hex'] != "undefined") {
4071 this.setValueHex(params['hex']);
4075 YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
4077 // ********************************************************************
4079 * class for ASN.1 DER encoded BitString primitive
4080 * @name KJUR.asn1.DERBitString
4081 * @class class for ASN.1 DER encoded BitString primitive
4082 * @extends KJUR.asn1.ASN1Object
4085 * As for argument 'params' for constructor, you can specify one of
4086 * following properties:
4088 * <li>bin - specify binary string (ex. '10111')</li>
4089 * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
4090 * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
4091 * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
4092 * argument for "BitString encapsulates" structure.</li>
4094 * NOTE1: 'params' can be omitted.<br/>
4095 * NOTE2: 'obj' parameter have been supported since
4096 * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
4098 * // default constructor
4099 * o = new KJUR.asn1.DERBitString();
4100 * // initialize with binary string
4101 * o = new KJUR.asn1.DERBitString({bin: "1011"});
4102 * // initialize with boolean array
4103 * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
4104 * // initialize with hexadecimal string (04 is unused bits)
4105 * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
4106 * // initialize with ASN1Util.newObject argument for encapsulated
4107 * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4108 * // above generates a ASN.1 data like this:
4109 * // BIT STRING, encapsulates {
4112 * // PrintableString 'aaa'
4116 KJUR.asn1.DERBitString = function(params) {
4117 if (params !== undefined && typeof params.obj !== "undefined") {
4118 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4119 params.hex = "00" + o.getEncodedHex();
4121 KJUR.asn1.DERBitString.superclass.constructor.call(this);
4125 * set ASN.1 value(V) by a hexadecimal string including unused bits
4126 * @name setHexValueIncludingUnusedBits
4127 * @memberOf KJUR.asn1.DERBitString#
4129 * @param {String} newHexStringIncludingUnusedBits
4131 this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
4133 this.isModified = true;
4134 this.hV = newHexStringIncludingUnusedBits;
4138 * set ASN.1 value(V) by unused bit and hexadecimal string of value
4139 * @name setUnusedBitsAndHexValue
4140 * @memberOf KJUR.asn1.DERBitString#
4142 * @param {Integer} unusedBits
4143 * @param {String} hValue
4145 this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
4146 if (unusedBits < 0 || 7 < unusedBits) {
4147 throw "unused bits shall be from 0 to 7: u = " + unusedBits;
4149 var hUnusedBits = "0" + unusedBits;
4151 this.isModified = true;
4152 this.hV = hUnusedBits + hValue;
4156 * set ASN.1 DER BitString by binary string<br/>
4157 * @name setByBinaryString
4158 * @memberOf KJUR.asn1.DERBitString#
4160 * @param {String} binaryString binary value string (i.e. '10111')
4162 * Its unused bits will be calculated automatically by length of
4163 * 'binaryValue'. <br/>
4164 * NOTE: Trailing zeros '0' will be ignored.
4166 * o = new KJUR.asn1.DERBitString();
4167 * o.setByBooleanArray("01011");
4169 this.setByBinaryString = function(binaryString) {
4170 binaryString = binaryString.replace(/0+$/, '');
4171 var unusedBits = 8 - binaryString.length % 8;
4172 if (unusedBits == 8) unusedBits = 0;
4173 for (var i = 0; i <= unusedBits; i++) {
4174 binaryString += '0';
4177 for (var i = 0; i < binaryString.length - 1; i += 8) {
4178 var b = binaryString.substr(i, 8);
4179 var x = parseInt(b, 2).toString(16);
4180 if (x.length == 1) x = '0' + x;
4184 this.isModified = true;
4185 this.hV = '0' + unusedBits + h;
4189 * set ASN.1 TLV value(V) by an array of boolean<br/>
4190 * @name setByBooleanArray
4191 * @memberOf KJUR.asn1.DERBitString#
4193 * @param {array} booleanArray array of boolean (ex. [true, false, true])
4195 * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
4197 * o = new KJUR.asn1.DERBitString();
4198 * o.setByBooleanArray([false, true, false, true, true]);
4200 this.setByBooleanArray = function(booleanArray) {
4202 for (var i = 0; i < booleanArray.length; i++) {
4203 if (booleanArray[i] == true) {
4209 this.setByBinaryString(s);
4213 * generate an array of falses with specified length<br/>
4214 * @name newFalseArray
4215 * @memberOf KJUR.asn1.DERBitString
4217 * @param {Integer} nLength length of array to generate
4218 * @return {array} array of boolean falses
4220 * This static method may be useful to initialize boolean array.
4222 * o = new KJUR.asn1.DERBitString();
4223 * o.newFalseArray(3) → [false, false, false]
4225 this.newFalseArray = function(nLength) {
4226 var a = new Array(nLength);
4227 for (var i = 0; i < nLength; i++) {
4233 this.getFreshValueHex = function() {
4237 if (typeof params != "undefined") {
4238 if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
4239 this.setHexValueIncludingUnusedBits(params);
4240 } else if (typeof params['hex'] != "undefined") {
4241 this.setHexValueIncludingUnusedBits(params['hex']);
4242 } else if (typeof params['bin'] != "undefined") {
4243 this.setByBinaryString(params['bin']);
4244 } else if (typeof params['array'] != "undefined") {
4245 this.setByBooleanArray(params['array']);
4249 YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
4251 // ********************************************************************
4253 * class for ASN.1 DER OctetString<br/>
4254 * @name KJUR.asn1.DEROctetString
4255 * @class class for ASN.1 DER OctetString
4256 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4257 * @extends KJUR.asn1.DERAbstractString
4259 * This class provides ASN.1 OctetString simple type.<br/>
4260 * Supported "params" attributes are:
4262 * <li>str - to set a string as a value</li>
4263 * <li>hex - to set a hexadecimal string as a value</li>
4264 * <li>obj - to set a encapsulated ASN.1 value by JSON object
4265 * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
4267 * NOTE: A parameter 'obj' have been supported
4268 * for "OCTET STRING, encapsulates" structure.
4269 * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
4270 * @see KJUR.asn1.DERAbstractString - superclass
4272 * // default constructor
4273 * o = new KJUR.asn1.DEROctetString();
4274 * // initialize with string
4275 * o = new KJUR.asn1.DEROctetString({str: "aaa"});
4276 * // initialize with hexadecimal string
4277 * o = new KJUR.asn1.DEROctetString({hex: "616161"});
4278 * // initialize with ASN1Util.newObject argument
4279 * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4280 * // above generates a ASN.1 data like this:
4281 * // OCTET STRING, encapsulates {
4284 * // PrintableString 'aaa'
4288 KJUR.asn1.DEROctetString = function(params) {
4289 if (params !== undefined && typeof params.obj !== "undefined") {
4290 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4291 params.hex = o.getEncodedHex();
4293 KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
4296 YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
4298 // ********************************************************************
4300 * class for ASN.1 DER Null
4301 * @name KJUR.asn1.DERNull
4302 * @class class for ASN.1 DER Null
4303 * @extends KJUR.asn1.ASN1Object
4305 * @see KJUR.asn1.ASN1Object - superclass
4307 KJUR.asn1.DERNull = function() {
4308 KJUR.asn1.DERNull.superclass.constructor.call(this);
4312 YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
4314 // ********************************************************************
4316 * class for ASN.1 DER ObjectIdentifier
4317 * @name KJUR.asn1.DERObjectIdentifier
4318 * @class class for ASN.1 DER ObjectIdentifier
4319 * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
4320 * @extends KJUR.asn1.ASN1Object
4323 * As for argument 'params' for constructor, you can specify one of
4324 * following properties:
4326 * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
4327 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4329 * NOTE: 'params' can be omitted.
4331 KJUR.asn1.DERObjectIdentifier = function(params) {
4332 var itox = function(i) {
4333 var h = i.toString(16);
4334 if (h.length == 1) h = '0' + h;
4337 var roidtox = function(roid) {
4339 var bi = new BigInteger(roid, 10);
4340 var b = bi.toString(2);
4341 var padLen = 7 - b.length % 7;
4342 if (padLen == 7) padLen = 0;
4344 for (var i = 0; i < padLen; i++) bPad += '0';
4346 for (var i = 0; i < b.length - 1; i += 7) {
4347 var b8 = b.substr(i, 7);
4348 if (i != b.length - 7) b8 = '1' + b8;
4349 h += itox(parseInt(b8, 2));
4354 KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
4358 * set value by a hexadecimal string
4360 * @memberOf KJUR.asn1.DERObjectIdentifier#
4362 * @param {String} newHexString hexadecimal value of OID bytes
4364 this.setValueHex = function(newHexString) {
4366 this.isModified = true;
4368 this.hV = newHexString;
4372 * set value by a OID string<br/>
4373 * @name setValueOidString
4374 * @memberOf KJUR.asn1.DERObjectIdentifier#
4376 * @param {String} oidString OID string (ex. 2.5.4.13)
4378 * o = new KJUR.asn1.DERObjectIdentifier();
4379 * o.setValueOidString("2.5.4.13");
4381 this.setValueOidString = function(oidString) {
4382 if (! oidString.match(/^[0-9.]+$/)) {
4383 throw "malformed oid string: " + oidString;
4386 var a = oidString.split('.');
4387 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
4390 for (var i = 0; i < a.length; i++) {
4394 this.isModified = true;
4400 * set value by a OID name
4401 * @name setValueName
4402 * @memberOf KJUR.asn1.DERObjectIdentifier#
4404 * @param {String} oidName OID name (ex. 'serverAuth')
4407 * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
4408 * Otherwise raise error.
4410 * o = new KJUR.asn1.DERObjectIdentifier();
4411 * o.setValueName("serverAuth");
4413 this.setValueName = function(oidName) {
4414 var oid = KJUR.asn1.x509.OID.name2oid(oidName);
4416 this.setValueOidString(oid);
4418 throw "DERObjectIdentifier oidName undefined: " + oidName;
4422 this.getFreshValueHex = function() {
4426 if (params !== undefined) {
4427 if (typeof params === "string") {
4428 if (params.match(/^[0-2].[0-9.]+$/)) {
4429 this.setValueOidString(params);
4431 this.setValueName(params);
4433 } else if (params.oid !== undefined) {
4434 this.setValueOidString(params.oid);
4435 } else if (params.hex !== undefined) {
4436 this.setValueHex(params.hex);
4437 } else if (params.name !== undefined) {
4438 this.setValueName(params.name);
4442 YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
4444 // ********************************************************************
4446 * class for ASN.1 DER Enumerated
4447 * @name KJUR.asn1.DEREnumerated
4448 * @class class for ASN.1 DER Enumerated
4449 * @extends KJUR.asn1.ASN1Object
4452 * As for argument 'params' for constructor, you can specify one of
4453 * following properties:
4455 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4456 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4458 * NOTE: 'params' can be omitted.
4460 * new KJUR.asn1.DEREnumerated(123);
4461 * new KJUR.asn1.DEREnumerated({int: 123});
4462 * new KJUR.asn1.DEREnumerated({hex: '1fad'});
4464 KJUR.asn1.DEREnumerated = function(params) {
4465 KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
4469 * set value by Tom Wu's BigInteger object
4470 * @name setByBigInteger
4471 * @memberOf KJUR.asn1.DEREnumerated#
4473 * @param {BigInteger} bigIntegerValue to set
4475 this.setByBigInteger = function(bigIntegerValue) {
4477 this.isModified = true;
4478 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4482 * set value by integer value
4483 * @name setByInteger
4484 * @memberOf KJUR.asn1.DEREnumerated#
4486 * @param {Integer} integer value to set
4488 this.setByInteger = function(intValue) {
4489 var bi = new BigInteger(String(intValue), 10);
4490 this.setByBigInteger(bi);
4494 * set value by integer value
4496 * @memberOf KJUR.asn1.DEREnumerated#
4498 * @param {String} hexadecimal string of integer value
4501 * NOTE: Value shall be represented by minimum octet length of
4502 * two's complement representation.
4504 this.setValueHex = function(newHexString) {
4505 this.hV = newHexString;
4508 this.getFreshValueHex = function() {
4512 if (typeof params != "undefined") {
4513 if (typeof params['int'] != "undefined") {
4514 this.setByInteger(params['int']);
4515 } else if (typeof params == "number") {
4516 this.setByInteger(params);
4517 } else if (typeof params['hex'] != "undefined") {
4518 this.setValueHex(params['hex']);
4522 YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
4524 // ********************************************************************
4526 * class for ASN.1 DER UTF8String
4527 * @name KJUR.asn1.DERUTF8String
4528 * @class class for ASN.1 DER UTF8String
4529 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4530 * @extends KJUR.asn1.DERAbstractString
4532 * @see KJUR.asn1.DERAbstractString - superclass
4534 KJUR.asn1.DERUTF8String = function(params) {
4535 KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
4538 YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
4540 // ********************************************************************
4542 * class for ASN.1 DER NumericString
4543 * @name KJUR.asn1.DERNumericString
4544 * @class class for ASN.1 DER NumericString
4545 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4546 * @extends KJUR.asn1.DERAbstractString
4548 * @see KJUR.asn1.DERAbstractString - superclass
4550 KJUR.asn1.DERNumericString = function(params) {
4551 KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
4554 YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
4556 // ********************************************************************
4558 * class for ASN.1 DER PrintableString
4559 * @name KJUR.asn1.DERPrintableString
4560 * @class class for ASN.1 DER PrintableString
4561 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4562 * @extends KJUR.asn1.DERAbstractString
4564 * @see KJUR.asn1.DERAbstractString - superclass
4566 KJUR.asn1.DERPrintableString = function(params) {
4567 KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
4570 YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
4572 // ********************************************************************
4574 * class for ASN.1 DER TeletexString
4575 * @name KJUR.asn1.DERTeletexString
4576 * @class class for ASN.1 DER TeletexString
4577 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4578 * @extends KJUR.asn1.DERAbstractString
4580 * @see KJUR.asn1.DERAbstractString - superclass
4582 KJUR.asn1.DERTeletexString = function(params) {
4583 KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
4586 YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
4588 // ********************************************************************
4590 * class for ASN.1 DER IA5String
4591 * @name KJUR.asn1.DERIA5String
4592 * @class class for ASN.1 DER IA5String
4593 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4594 * @extends KJUR.asn1.DERAbstractString
4596 * @see KJUR.asn1.DERAbstractString - superclass
4598 KJUR.asn1.DERIA5String = function(params) {
4599 KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
4602 YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
4604 // ********************************************************************
4606 * class for ASN.1 DER UTCTime
4607 * @name KJUR.asn1.DERUTCTime
4608 * @class class for ASN.1 DER UTCTime
4609 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
4610 * @extends KJUR.asn1.DERAbstractTime
4613 * As for argument 'params' for constructor, you can specify one of
4614 * following properties:
4616 * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
4617 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4618 * <li>date - specify Date object.</li>
4620 * NOTE: 'params' can be omitted.
4623 * d1 = new KJUR.asn1.DERUTCTime();
4624 * d1.setString('130430125959Z');
4626 * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
4627 * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
4628 * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
4630 KJUR.asn1.DERUTCTime = function(params) {
4631 KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
4635 * set value by a Date object<br/>
4637 * @memberOf KJUR.asn1.DERUTCTime#
4639 * @param {Date} dateObject Date object to set ASN.1 value(V)
4641 * o = new KJUR.asn1.DERUTCTime();
4642 * o.setByDate(new Date("2016/12/31"));
4644 this.setByDate = function(dateObject) {
4646 this.isModified = true;
4647 this.date = dateObject;
4648 this.s = this.formatDate(this.date, 'utc');
4649 this.hV = stohex(this.s);
4652 this.getFreshValueHex = function() {
4653 if (typeof this.date == "undefined" && typeof this.s == "undefined") {
4654 this.date = new Date();
4655 this.s = this.formatDate(this.date, 'utc');
4656 this.hV = stohex(this.s);
4661 if (params !== undefined) {
4662 if (params.str !== undefined) {
4663 this.setString(params.str);
4664 } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
4665 this.setString(params);
4666 } else if (params.hex !== undefined) {
4667 this.setStringHex(params.hex);
4668 } else if (params.date !== undefined) {
4669 this.setByDate(params.date);
4673 YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
4675 // ********************************************************************
4677 * class for ASN.1 DER GeneralizedTime
4678 * @name KJUR.asn1.DERGeneralizedTime
4679 * @class class for ASN.1 DER GeneralizedTime
4680 * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
4681 * @property {Boolean} withMillis flag to show milliseconds or not
4682 * @extends KJUR.asn1.DERAbstractTime
4685 * As for argument 'params' for constructor, you can specify one of
4686 * following properties:
4688 * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
4689 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4690 * <li>date - specify Date object.</li>
4691 * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
4693 * NOTE1: 'params' can be omitted.
4694 * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
4696 KJUR.asn1.DERGeneralizedTime = function(params) {
4697 KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
4699 this.withMillis = false;
4702 * set value by a Date object
4704 * @memberOf KJUR.asn1.DERGeneralizedTime#
4706 * @param {Date} dateObject Date object to set ASN.1 value(V)
4708 * When you specify UTC time, use 'Date.UTC' method like this:<br/>
4709 * o1 = new DERUTCTime();
4710 * o1.setByDate(date);
4712 * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
4714 this.setByDate = function(dateObject) {
4716 this.isModified = true;
4717 this.date = dateObject;
4718 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4719 this.hV = stohex(this.s);
4722 this.getFreshValueHex = function() {
4723 if (this.date === undefined && this.s === undefined) {
4724 this.date = new Date();
4725 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4726 this.hV = stohex(this.s);
4731 if (params !== undefined) {
4732 if (params.str !== undefined) {
4733 this.setString(params.str);
4734 } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
4735 this.setString(params);
4736 } else if (params.hex !== undefined) {
4737 this.setStringHex(params.hex);
4738 } else if (params.date !== undefined) {
4739 this.setByDate(params.date);
4741 if (params.millis === true) {
4742 this.withMillis = true;
4746 YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
4748 // ********************************************************************
4750 * class for ASN.1 DER Sequence
4751 * @name KJUR.asn1.DERSequence
4752 * @class class for ASN.1 DER Sequence
4753 * @extends KJUR.asn1.DERAbstractStructured
4756 * As for argument 'params' for constructor, you can specify one of
4757 * following properties:
4759 * <li>array - specify array of ASN1Object to set elements of content</li>
4761 * NOTE: 'params' can be omitted.
4763 KJUR.asn1.DERSequence = function(params) {
4764 KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
4766 this.getFreshValueHex = function() {
4768 for (var i = 0; i < this.asn1Array.length; i++) {
4769 var asn1Obj = this.asn1Array[i];
4770 h += asn1Obj.getEncodedHex();
4776 YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
4778 // ********************************************************************
4780 * class for ASN.1 DER Set
4781 * @name KJUR.asn1.DERSet
4782 * @class class for ASN.1 DER Set
4783 * @extends KJUR.asn1.DERAbstractStructured
4786 * As for argument 'params' for constructor, you can specify one of
4787 * following properties:
4789 * <li>array - specify array of ASN1Object to set elements of content</li>
4790 * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
4792 * NOTE1: 'params' can be omitted.<br/>
4793 * NOTE2: sortflag is supported since 1.0.5.
4795 KJUR.asn1.DERSet = function(params) {
4796 KJUR.asn1.DERSet.superclass.constructor.call(this, params);
4798 this.sortFlag = true; // item shall be sorted only in ASN.1 DER
4799 this.getFreshValueHex = function() {
4800 var a = new Array();
4801 for (var i = 0; i < this.asn1Array.length; i++) {
4802 var asn1Obj = this.asn1Array[i];
4803 a.push(asn1Obj.getEncodedHex());
4805 if (this.sortFlag == true) a.sort();
4806 this.hV = a.join('');
4810 if (typeof params != "undefined") {
4811 if (typeof params.sortflag != "undefined" &&
4812 params.sortflag == false)
4813 this.sortFlag = false;
4816 YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
4818 // ********************************************************************
4820 * class for ASN.1 DER TaggedObject
4821 * @name KJUR.asn1.DERTaggedObject
4822 * @class class for ASN.1 DER TaggedObject
4823 * @extends KJUR.asn1.ASN1Object
4826 * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
4827 * For example, if you find '[1]' tag in a ASN.1 dump,
4828 * 'tagNoHex' will be 'a1'.
4830 * As for optional argument 'params' for constructor, you can specify *ANY* of
4831 * following properties:
4833 * <li>explicit - specify true if this is explicit tag otherwise false
4834 * (default is 'true').</li>
4835 * <li>tag - specify tag (default is 'a0' which means [0])</li>
4836 * <li>obj - specify ASN1Object which is tagged</li>
4839 * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
4840 * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
4841 * hex = d2.getEncodedHex();
4843 KJUR.asn1.DERTaggedObject = function(params) {
4844 KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
4847 this.isExplicit = true;
4848 this.asn1Object = null;
4851 * set value by an ASN1Object
4853 * @memberOf KJUR.asn1.DERTaggedObject#
4855 * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
4856 * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
4857 * @param {ASN1Object} asn1Object ASN.1 to encapsulate
4859 this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
4861 this.isExplicit = isExplicitFlag;
4862 this.asn1Object = asn1Object;
4863 if (this.isExplicit) {
4864 this.hV = this.asn1Object.getEncodedHex();
4866 this.isModified = true;
4869 this.hTLV = asn1Object.getEncodedHex();
4870 this.hTLV = this.hTLV.replace(/^../, tagNoHex);
4871 this.isModified = false;
4875 this.getFreshValueHex = function() {
4879 if (typeof params != "undefined") {
4880 if (typeof params['tag'] != "undefined") {
4881 this.hT = params['tag'];
4883 if (typeof params['explicit'] != "undefined") {
4884 this.isExplicit = params['explicit'];
4886 if (typeof params['obj'] != "undefined") {
4887 this.asn1Object = params['obj'];
4888 this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
4892 YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
4895 * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
4896 * This object is just a decorator for parsing the key parameter
4897 * @param {string|Object} key - The key in string format, or an object containing
4898 * the parameters needed to build a RSAKey object.
4901 var JSEncryptRSAKey = /** @class */ (function (_super) {
4902 __extends(JSEncryptRSAKey, _super);
4903 function JSEncryptRSAKey(key) {
4904 var _this = _super.call(this) || this;
4905 // Call the super constructor.
4906 // RSAKey.call(this);
4907 // If a key key was provided.
4909 // If this is a string...
4910 if (typeof key === "string") {
4911 _this.parseKey(key);
4913 else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
4914 JSEncryptRSAKey.hasPublicKeyProperty(key)) {
4915 // Set the values for the key.
4916 _this.parsePropertiesFrom(key);
4922 * Method to parse a pem encoded string containing both a public or private key.
4923 * The method will translate the pem encoded string in a der encoded string and
4924 * will parse private key and public key parameters. This method accepts public key
4925 * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
4927 * @todo Check how many rsa formats use the same format of pkcs #1.
4929 * The format is defined as:
4930 * PublicKeyInfo ::= SEQUENCE {
4931 * algorithm AlgorithmIdentifier,
4932 * PublicKey BIT STRING
4934 * Where AlgorithmIdentifier is:
4935 * AlgorithmIdentifier ::= SEQUENCE {
4936 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
4937 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
4939 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
4940 * RSAPublicKey ::= SEQUENCE {
4941 * modulus INTEGER, -- n
4942 * publicExponent INTEGER -- e
4944 * it's possible to examine the structure of the keys obtained from openssl using
4945 * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
4946 * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
4949 JSEncryptRSAKey.prototype.parseKey = function (pem) {
4952 var public_exponent = 0;
4953 var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
4954 var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
4955 var asn1 = ASN1.decode(der);
4956 // Fixes a bug with OpenSSL 1.0+ private keys
4957 if (asn1.sub.length === 3) {
4958 asn1 = asn1.sub[2].sub[0];
4960 if (asn1.sub.length === 9) {
4961 // Parse the private key.
4962 modulus = asn1.sub[1].getHexStringValue(); // bigint
4963 this.n = parseBigInt(modulus, 16);
4964 public_exponent = asn1.sub[2].getHexStringValue(); // int
4965 this.e = parseInt(public_exponent, 16);
4966 var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
4967 this.d = parseBigInt(private_exponent, 16);
4968 var prime1 = asn1.sub[4].getHexStringValue(); // bigint
4969 this.p = parseBigInt(prime1, 16);
4970 var prime2 = asn1.sub[5].getHexStringValue(); // bigint
4971 this.q = parseBigInt(prime2, 16);
4972 var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
4973 this.dmp1 = parseBigInt(exponent1, 16);
4974 var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
4975 this.dmq1 = parseBigInt(exponent2, 16);
4976 var coefficient = asn1.sub[8].getHexStringValue(); // bigint
4977 this.coeff = parseBigInt(coefficient, 16);
4979 else if (asn1.sub.length === 2) {
4980 // Parse the public key.
4981 var bit_string = asn1.sub[1];
4982 var sequence = bit_string.sub[0];
4983 modulus = sequence.sub[0].getHexStringValue();
4984 this.n = parseBigInt(modulus, 16);
4985 public_exponent = sequence.sub[1].getHexStringValue();
4986 this.e = parseInt(public_exponent, 16);
4998 * Translate rsa parameters in a hex encoded string representing the rsa key.
5000 * The translation follow the ASN.1 notation :
5001 * RSAPrivateKey ::= SEQUENCE {
5003 * modulus INTEGER, -- n
5004 * publicExponent INTEGER, -- e
5005 * privateExponent INTEGER, -- d
5006 * prime1 INTEGER, -- p
5007 * prime2 INTEGER, -- q
5008 * exponent1 INTEGER, -- d mod (p1)
5009 * exponent2 INTEGER, -- d mod (q-1)
5010 * coefficient INTEGER, -- (inverse of q) mod p
5012 * @returns {string} DER Encoded String representing the rsa private key
5015 JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
5018 new KJUR.asn1.DERInteger({ int: 0 }),
5019 new KJUR.asn1.DERInteger({ bigint: this.n }),
5020 new KJUR.asn1.DERInteger({ int: this.e }),
5021 new KJUR.asn1.DERInteger({ bigint: this.d }),
5022 new KJUR.asn1.DERInteger({ bigint: this.p }),
5023 new KJUR.asn1.DERInteger({ bigint: this.q }),
5024 new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
5025 new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
5026 new KJUR.asn1.DERInteger({ bigint: this.coeff })
5029 var seq = new KJUR.asn1.DERSequence(options);
5030 return seq.getEncodedHex();
5033 * base64 (pem) encoded version of the DER encoded representation
5034 * @returns {string} pem encoded representation without header and footer
5037 JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
5038 return hex2b64(this.getPrivateBaseKey());
5041 * Translate rsa parameters in a hex encoded string representing the rsa public key.
5042 * The representation follow the ASN.1 notation :
5043 * PublicKeyInfo ::= SEQUENCE {
5044 * algorithm AlgorithmIdentifier,
5045 * PublicKey BIT STRING
5047 * Where AlgorithmIdentifier is:
5048 * AlgorithmIdentifier ::= SEQUENCE {
5049 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
5050 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
5052 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
5053 * RSAPublicKey ::= SEQUENCE {
5054 * modulus INTEGER, -- n
5055 * publicExponent INTEGER -- e
5057 * @returns {string} DER Encoded String representing the rsa public key
5060 JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
5061 var first_sequence = new KJUR.asn1.DERSequence({
5063 new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
5064 new KJUR.asn1.DERNull()
5067 var second_sequence = new KJUR.asn1.DERSequence({
5069 new KJUR.asn1.DERInteger({ bigint: this.n }),
5070 new KJUR.asn1.DERInteger({ int: this.e })
5073 var bit_string = new KJUR.asn1.DERBitString({
5074 hex: "00" + second_sequence.getEncodedHex()
5076 var seq = new KJUR.asn1.DERSequence({
5082 return seq.getEncodedHex();
5085 * base64 (pem) encoded version of the DER encoded representation
5086 * @returns {string} pem encoded representation without header and footer
5089 JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
5090 return hex2b64(this.getPublicBaseKey());
5093 * wrap the string in block of width chars. The default value for rsa keys is 64
5095 * @param {string} str the pem encoded string without header and footer
5096 * @param {Number} [width=64] - the length the string has to be wrapped at
5100 JSEncryptRSAKey.wordwrap = function (str, width) {
5101 width = width || 64;
5105 var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
5106 return str.match(RegExp(regex, "g")).join("\n");
5109 * Retrieve the pem encoded private key
5110 * @returns {string} the pem encoded private key with header/footer
5113 JSEncryptRSAKey.prototype.getPrivateKey = function () {
5114 var key = "-----BEGIN RSA PRIVATE KEY-----\n";
5115 key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
5116 key += "-----END RSA PRIVATE KEY-----";
5120 * Retrieve the pem encoded public key
5121 * @returns {string} the pem encoded public key with header/footer
5124 JSEncryptRSAKey.prototype.getPublicKey = function () {
5125 var key = "-----BEGIN PUBLIC KEY-----\n";
5126 key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
5127 key += "-----END PUBLIC KEY-----";
5131 * Check if the object contains the necessary parameters to populate the rsa modulus
5132 * and public exponent parameters.
5133 * @param {Object} [obj={}] - An object that may contain the two public key
5135 * @returns {boolean} true if the object contains both the modulus and the public exponent
5136 * properties (n and e)
5137 * @todo check for types of n and e. N should be a parseable bigInt object, E should
5138 * be a parseable integer number
5141 JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
5143 return (obj.hasOwnProperty("n") &&
5144 obj.hasOwnProperty("e"));
5147 * Check if the object contains ALL the parameters of an RSA key.
5148 * @param {Object} [obj={}] - An object that may contain nine rsa key
5150 * @returns {boolean} true if the object contains all the parameters needed
5151 * @todo check for types of the parameters all the parameters but the public exponent
5152 * should be parseable bigint objects, the public exponent should be a parseable integer number
5155 JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
5157 return (obj.hasOwnProperty("n") &&
5158 obj.hasOwnProperty("e") &&
5159 obj.hasOwnProperty("d") &&
5160 obj.hasOwnProperty("p") &&
5161 obj.hasOwnProperty("q") &&
5162 obj.hasOwnProperty("dmp1") &&
5163 obj.hasOwnProperty("dmq1") &&
5164 obj.hasOwnProperty("coeff"));
5167 * Parse the properties of obj in the current rsa object. Obj should AT LEAST
5168 * include the modulus and public exponent (n, e) parameters.
5169 * @param {Object} obj - the object containing rsa parameters
5172 JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
5175 if (obj.hasOwnProperty("d")) {
5179 this.dmp1 = obj.dmp1;
5180 this.dmq1 = obj.dmq1;
5181 this.coeff = obj.coeff;
5184 return JSEncryptRSAKey;
5189 * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
5190 * possible parameters are:
5191 * - default_key_size {number} default: 1024 the key size in bit
5192 * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
5193 * - log {boolean} default: false whether log warn/error or not
5196 var JSEncrypt = /** @class */ (function () {
5197 function JSEncrypt(options) {
5198 options = options || {};
5199 this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
5200 this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
5201 this.log = options.log || false;
5202 // The private and public key.
5206 * Method to set the rsa key parameter (one method is enough to set both the public
5207 * and the private key, since the private key contains the public key paramenters)
5208 * Log a warning if logs are enabled
5209 * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
5212 JSEncrypt.prototype.setKey = function (key) {
5213 if (this.log && this.key) {
5214 console.warn("A key was already set, overriding existing.");
5216 this.key = new JSEncryptRSAKey(key);
5219 * Proxy method for setKey, for api compatibility
5223 JSEncrypt.prototype.setPrivateKey = function (privkey) {
5225 this.setKey(privkey);
5228 * Proxy method for setKey, for api compatibility
5232 JSEncrypt.prototype.setPublicKey = function (pubkey) {
5233 // Sets the public key.
5234 this.setKey(pubkey);
5237 * Proxy method for RSAKey object's decrypt, decrypt the string using the private
5238 * components of the rsa key object. Note that if the object was not set will be created
5239 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5240 * @param {string} str base64 encoded crypted string to decrypt
5241 * @return {string} the decrypted string
5244 JSEncrypt.prototype.decrypt = function (str) {
5245 // Return the decrypted string.
5247 return this.getKey().decrypt(b64tohex(str));
5254 * Proxy method for RSAKey object's encrypt, encrypt the string using the public
5255 * components of the rsa key object. Note that if the object was not set will be created
5256 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5257 * @param {string} str the string to encrypt
5258 * @return {string} the encrypted string encoded in base64
5261 JSEncrypt.prototype.encrypt = function (str) {
5262 // Return the encrypted string.
5264 return hex2b64(this.getKey().encrypt(str));
5271 * Proxy method for RSAKey object's sign.
5272 * @param {string} str the string to sign
5273 * @param {function} digestMethod hash method
5274 * @param {string} digestName the name of the hash algorithm
5275 * @return {string} the signature encoded in base64
5278 JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
5279 // return the RSA signature of 'str' in 'hex' format.
5281 return hex2b64(this.getKey().sign(str, digestMethod, digestName));
5288 * Proxy method for RSAKey object's verify.
5289 * @param {string} str the string to verify
5290 * @param {string} signature the signature encoded in base64 to compare the string to
5291 * @param {function} digestMethod hash method
5292 * @return {boolean} whether the data and signature match
5295 JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
5296 // Return the decrypted 'digest' of the signature.
5298 return this.getKey().verify(str, b64tohex(signature), digestMethod);
5305 * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
5306 * will be created and returned
5307 * @param {callback} [cb] the callback to be called if we want the key to be generated
5308 * in an async fashion
5309 * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
5312 JSEncrypt.prototype.getKey = function (cb) {
5313 // Only create new if it does not exist.
5315 // Get a new private key.
5316 this.key = new JSEncryptRSAKey();
5317 if (cb && {}.toString.call(cb) === "[object Function]") {
5318 this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
5321 // Generate the key.
5322 this.key.generate(this.default_key_size, this.default_public_exponent);
5327 * Returns the pem encoded representation of the private key
5328 * If the key doesn't exists a new key will be created
5329 * @returns {string} pem encoded representation of the private key WITH header and footer
5332 JSEncrypt.prototype.getPrivateKey = function () {
5333 // Return the private representation of this key.
5334 return this.getKey().getPrivateKey();
5337 * Returns the pem encoded representation of the private key
5338 * If the key doesn't exists a new key will be created
5339 * @returns {string} pem encoded representation of the private key WITHOUT header and footer
5342 JSEncrypt.prototype.getPrivateKeyB64 = function () {
5343 // Return the private representation of this key.
5344 return this.getKey().getPrivateBaseKeyB64();
5347 * Returns the pem encoded representation of the public key
5348 * If the key doesn't exists a new key will be created
5349 * @returns {string} pem encoded representation of the public key WITH header and footer
5352 JSEncrypt.prototype.getPublicKey = function () {
5353 // Return the private representation of this key.
5354 return this.getKey().getPublicKey();
5357 * Returns the pem encoded representation of the public key
5358 * If the key doesn't exists a new key will be created
5359 * @returns {string} pem encoded representation of the public key WITHOUT header and footer
5362 JSEncrypt.prototype.getPublicKeyB64 = function () {
5363 // Return the private representation of this key.
5364 return this.getKey().getPublicBaseKeyB64();
5366 JSEncrypt.version = "3.0.0-rc.1";
5370 window.JSEncrypt = JSEncrypt;
5372 exports.JSEncrypt = JSEncrypt;
5373 exports.default = JSEncrypt;
5375 Object.defineProperty(exports, '__esModule', { value: true });