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 return BI_RM.charAt(n);
11 //#region BIT_OPERATIONS
13 function op_and(x, y) {
17 function op_or(x, y) {
21 function op_xor(x, y) {
25 function op_andnot(x, y) {
28 // return index of lowest 1-bit in x, x < 2^31
34 if ((x & 0xffff) == 0) {
38 if ((x & 0xff) == 0) {
55 // return number of 1 bits in x
64 //#endregion BIT_OPERATIONS
66 var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
72 for (i = 0; i + 3 <= h.length; i += 3) {
73 c = parseInt(h.substring(i, i + 3), 16);
74 ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
76 if (i + 1 == h.length) {
77 c = parseInt(h.substring(i, i + 1), 16);
78 ret += b64map.charAt(c << 2);
80 else if (i + 2 == h.length) {
81 c = parseInt(h.substring(i, i + 2), 16);
82 ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
84 while ((ret.length & 3) > 0) {
89 // convert a base64 string to hex
90 function b64tohex(s) {
93 var k = 0; // b64 state, 0-3
95 for (i = 0; i < s.length; ++i) {
96 if (s.charAt(i) == b64pad) {
99 var v = b64map.indexOf(s.charAt(i));
104 ret += int2char(v >> 2);
109 ret += int2char((slop << 2) | (v >> 4));
114 ret += int2char(slop);
115 ret += int2char(v >> 2);
120 ret += int2char((slop << 2) | (v >> 4));
121 ret += int2char(v & 0xf);
126 ret += int2char(slop << 2);
131 /*! *****************************************************************************
132 Copyright (c) Microsoft Corporation. All rights reserved.
133 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
134 this file except in compliance with the License. You may obtain a copy of the
135 License at http://www.apache.org/licenses/LICENSE-2.0
136 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
137 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
138 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
139 MERCHANTABLITY OR NON-INFRINGEMENT.
140 See the Apache Version 2.0 License for specific language governing permissions
141 and limitations under the License.
142 ***************************************************************************** */
143 /* global Reflect, Promise */
145 var extendStatics = function(d, b) {
146 extendStatics = Object.setPrototypeOf ||
147 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
148 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
149 return extendStatics(d, b);
152 function __extends(d, b) {
154 function __() { this.constructor = d; }
155 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
158 // Hex JavaScript decoder
159 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
160 // Permission to use, copy, modify, and/or distribute this software for any
161 // purpose with or without fee is hereby granted, provided that the above
162 // copyright notice and this permission notice appear in all copies.
164 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
165 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
166 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
167 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
168 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
169 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
170 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
171 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
174 decode: function (a) {
176 if (decoder === undefined) {
177 var hex = "0123456789ABCDEF";
178 var ignore = " \f\n\r\t\u00A0\u2028\u2029";
180 for (i = 0; i < 16; ++i) {
181 decoder[hex.charAt(i)] = i;
183 hex = hex.toLowerCase();
184 for (i = 10; i < 16; ++i) {
185 decoder[hex.charAt(i)] = i;
187 for (i = 0; i < ignore.length; ++i) {
188 decoder[ignore.charAt(i)] = -1;
194 for (i = 0; i < a.length; ++i) {
203 if (c === undefined) {
204 throw new Error("Illegal character at offset " + i);
207 if (++char_count >= 2) {
208 out[out.length] = bits;
217 throw new Error("Hex encoding incomplete: 4 bits missing");
223 // Base64 JavaScript decoder
224 // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
225 // Permission to use, copy, modify, and/or distribute this software for any
226 // purpose with or without fee is hereby granted, provided that the above
227 // copyright notice and this permission notice appear in all copies.
229 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
230 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
231 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
232 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
233 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
234 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
235 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
236 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
239 decode: function (a) {
241 if (decoder$1 === undefined) {
242 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
243 var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
244 decoder$1 = Object.create(null);
245 for (i = 0; i < 64; ++i) {
246 decoder$1[b64.charAt(i)] = i;
248 for (i = 0; i < ignore.length; ++i) {
249 decoder$1[ignore.charAt(i)] = -1;
255 for (i = 0; i < a.length; ++i) {
264 if (c === undefined) {
265 throw new Error("Illegal character at offset " + i);
268 if (++char_count >= 4) {
269 out[out.length] = (bits >> 16);
270 out[out.length] = (bits >> 8) & 0xFF;
271 out[out.length] = bits & 0xFF;
279 switch (char_count) {
281 throw new Error("Base64 encoding incomplete: at least 2 bits missing");
283 out[out.length] = (bits >> 10);
286 out[out.length] = (bits >> 16);
287 out[out.length] = (bits >> 8) & 0xFF;
292 re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
293 unarmor: function (a) {
294 var m = Base64.re.exec(a);
303 throw new Error("RegExp out of sync");
306 return Base64.decode(a);
310 // Big integer base-10 printing library
311 // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
312 // Permission to use, copy, modify, and/or distribute this software for any
313 // purpose with or without fee is hereby granted, provided that the above
314 // copyright notice and this permission notice appear in all copies.
316 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
317 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
318 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
319 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
320 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
321 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
322 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
323 /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
324 var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
325 var Int10 = /** @class */ (function () {
326 function Int10(value) {
327 this.buf = [+value || 0];
329 Int10.prototype.mulAdd = function (m, c) {
335 for (i = 0; i < l; ++i) {
350 Int10.prototype.sub = function (c) {
356 for (i = 0; i < l; ++i) {
367 while (b[b.length - 1] === 0) {
371 Int10.prototype.toString = function (base) {
372 if ((base || 10) != 10) {
373 throw new Error("only base 10 is supported");
376 var s = b[b.length - 1].toString();
377 for (var i = b.length - 2; i >= 0; --i) {
378 s += (max + b[i]).toString().substring(1);
382 Int10.prototype.valueOf = function () {
385 for (var i = b.length - 1; i >= 0; --i) {
390 Int10.prototype.simplify = function () {
392 return (b.length == 1) ? b[0] : this;
397 // ASN.1 JavaScript decoder
398 var ellipsis = "\u2026";
399 var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
400 var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
401 function stringCut(str, len) {
402 if (str.length > len) {
403 str = str.substring(0, len) + ellipsis;
407 var Stream = /** @class */ (function () {
408 function Stream(enc, pos) {
409 this.hexDigits = "0123456789ABCDEF";
410 if (enc instanceof Stream) {
415 // enc should be an array or a binary string
420 Stream.prototype.get = function (pos) {
421 if (pos === undefined) {
424 if (pos >= this.enc.length) {
425 throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
427 return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
429 Stream.prototype.hexByte = function (b) {
430 return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
432 Stream.prototype.hexDump = function (start, end, raw) {
434 for (var i = start; i < end; ++i) {
435 s += this.hexByte(this.get(i));
451 Stream.prototype.isASCII = function (start, end) {
452 for (var i = start; i < end; ++i) {
454 if (c < 32 || c > 176) {
460 Stream.prototype.parseStringISO = function (start, end) {
462 for (var i = start; i < end; ++i) {
463 s += String.fromCharCode(this.get(i));
467 Stream.prototype.parseStringUTF = function (start, end) {
469 for (var i = start; i < end;) {
470 var c = this.get(i++);
472 s += String.fromCharCode(c);
474 else if ((c > 191) && (c < 224)) {
475 s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
478 s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
483 Stream.prototype.parseStringBMP = function (start, end) {
487 for (var i = start; i < end;) {
490 str += String.fromCharCode((hi << 8) | lo);
494 Stream.prototype.parseTime = function (start, end, shortYear) {
495 var s = this.parseStringISO(start, end);
496 var m = (shortYear ? reTimeS : reTimeL).exec(s);
498 return "Unrecognized time: " + s;
501 // to avoid querying the timer, use the fixed range [1970, 2069]
502 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
504 m[1] += (+m[1] < 70) ? 2000 : 1900;
506 s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
527 Stream.prototype.parseInteger = function (start, end) {
528 var v = this.get(start);
530 var pad = neg ? 255 : 0;
533 // skip unuseful bits (not allowed in DER)
534 while (v == pad && ++start < end) {
541 // show bit length of huge integers
545 while (((+s ^ pad) & 0x80) == 0) {
549 s = "(" + len + " bit)\n";
551 // decode the integer
555 var n = new Int10(v);
556 for (var i = start + 1; i < end; ++i) {
557 n.mulAdd(256, this.get(i));
559 return s + n.toString();
561 Stream.prototype.parseBitString = function (start, end, maxLength) {
562 var unusedBit = this.get(start);
563 var lenBit = ((end - start - 1) << 3) - unusedBit;
564 var intro = "(" + lenBit + " bit)\n";
566 for (var i = start + 1; i < end; ++i) {
568 var skip = (i == end - 1) ? unusedBit : 0;
569 for (var j = 7; j >= skip; --j) {
570 s += (b >> j) & 1 ? "1" : "0";
572 if (s.length > maxLength) {
573 return intro + stringCut(s, maxLength);
578 Stream.prototype.parseOctetString = function (start, end, maxLength) {
579 if (this.isASCII(start, end)) {
580 return stringCut(this.parseStringISO(start, end), maxLength);
582 var len = end - start;
583 var s = "(" + len + " byte)\n";
584 maxLength /= 2; // we work in bytes
585 if (len > maxLength) {
586 end = start + maxLength;
588 for (var i = start; i < end; ++i) {
589 s += this.hexByte(this.get(i));
591 if (len > maxLength) {
596 Stream.prototype.parseOID = function (start, end, maxLength) {
600 for (var i = start; i < end; ++i) {
602 n.mulAdd(128, v & 0x7F);
604 if (!(v & 0x80)) { // finished
607 if (n instanceof Int10) {
609 s = "2." + n.toString();
612 var m = n < 80 ? n < 40 ? 0 : 1 : 2;
613 s = m + "." + (n - m * 40);
617 s += "." + n.toString();
619 if (s.length > maxLength) {
620 return stringCut(s, maxLength);
633 var ASN1 = /** @class */ (function () {
634 function ASN1(stream, header, length, tag, sub) {
635 if (!(tag instanceof ASN1Tag)) {
636 throw new Error("Invalid tag value.");
638 this.stream = stream;
639 this.header = header;
640 this.length = length;
644 ASN1.prototype.typeName = function () {
645 switch (this.tag.tagClass) {
647 switch (this.tag.tagNumber) {
657 return "OCTET_STRING";
661 return "OBJECT_IDENTIFIER";
663 return "ObjectDescriptor";
671 return "EMBEDDED_PDV";
679 return "NumericString";
681 return "PrintableString"; // ASCII subset
683 return "TeletexString"; // aka T61String
685 return "VideotexString";
687 return "IA5String"; // ASCII
691 return "GeneralizedTime";
693 return "GraphicString";
695 return "VisibleString"; // ASCII subset
697 return "GeneralString";
699 return "UniversalString";
703 return "Universal_" + this.tag.tagNumber.toString();
705 return "Application_" + this.tag.tagNumber.toString();
707 return "[" + this.tag.tagNumber.toString() + "]"; // Context
709 return "Private_" + this.tag.tagNumber.toString();
712 ASN1.prototype.content = function (maxLength) {
713 if (this.tag === undefined) {
716 if (maxLength === undefined) {
717 maxLength = Infinity;
719 var content = this.posContent();
720 var len = Math.abs(this.length);
721 if (!this.tag.isUniversal()) {
722 if (this.sub !== null) {
723 return "(" + this.sub.length + " elem)";
725 return this.stream.parseOctetString(content, content + len, maxLength);
727 switch (this.tag.tagNumber) {
728 case 0x01: // BOOLEAN
729 return (this.stream.get(content) === 0) ? "false" : "true";
730 case 0x02: // INTEGER
731 return this.stream.parseInteger(content, content + len);
732 case 0x03: // BIT_STRING
733 return this.sub ? "(" + this.sub.length + " elem)" :
734 this.stream.parseBitString(content, content + len, maxLength);
735 case 0x04: // OCTET_STRING
736 return this.sub ? "(" + this.sub.length + " elem)" :
737 this.stream.parseOctetString(content, content + len, maxLength);
738 // case 0x05: // NULL
739 case 0x06: // OBJECT_IDENTIFIER
740 return this.stream.parseOID(content, content + len, maxLength);
741 // case 0x07: // ObjectDescriptor
742 // case 0x08: // EXTERNAL
743 // case 0x09: // REAL
744 // case 0x0A: // ENUMERATED
745 // case 0x0B: // EMBEDDED_PDV
746 case 0x10: // SEQUENCE
748 if (this.sub !== null) {
749 return "(" + this.sub.length + " elem)";
754 case 0x0C: // UTF8String
755 return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
756 case 0x12: // NumericString
757 case 0x13: // PrintableString
758 case 0x14: // TeletexString
759 case 0x15: // VideotexString
760 case 0x16: // IA5String
761 // case 0x19: // GraphicString
762 case 0x1A: // VisibleString
763 // case 0x1B: // GeneralString
764 // case 0x1C: // UniversalString
765 return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
766 case 0x1E: // BMPString
767 return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
768 case 0x17: // UTCTime
769 case 0x18: // GeneralizedTime
770 return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
774 ASN1.prototype.toString = function () {
775 return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
777 ASN1.prototype.toPrettyString = function (indent) {
778 if (indent === undefined) {
781 var s = indent + this.typeName() + " @" + this.stream.pos;
782 if (this.length >= 0) {
786 if (this.tag.tagConstructed) {
787 s += " (constructed)";
789 else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
790 s += " (encapsulates)";
793 if (this.sub !== null) {
795 for (var i = 0, max = this.sub.length; i < max; ++i) {
796 s += this.sub[i].toPrettyString(indent);
801 ASN1.prototype.posStart = function () {
802 return this.stream.pos;
804 ASN1.prototype.posContent = function () {
805 return this.stream.pos + this.header;
807 ASN1.prototype.posEnd = function () {
808 return this.stream.pos + this.header + Math.abs(this.length);
810 ASN1.prototype.toHexString = function () {
811 return this.stream.hexDump(this.posStart(), this.posEnd(), true);
813 ASN1.decodeLength = function (stream) {
814 var buf = stream.get();
815 var len = buf & 0x7F;
819 // no reason to use Int10, as it would be a huge buffer anyways
821 throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
827 for (var i = 0; i < len; ++i) {
828 buf = (buf * 256) + stream.get();
833 * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
837 ASN1.prototype.getHexStringValue = function () {
838 var hexString = this.toHexString();
839 var offset = this.header * 2;
840 var length = this.length * 2;
841 return hexString.substr(offset, length);
843 ASN1.decode = function (str) {
845 if (!(str instanceof Stream)) {
846 stream = new Stream(str, 0);
851 var streamStart = new Stream(stream);
852 var tag = new ASN1Tag(stream);
853 var len = ASN1.decodeLength(stream);
854 var start = stream.pos;
855 var header = start - streamStart.pos;
857 var getSub = function () {
861 var end = start + len;
862 while (stream.pos < end) {
863 ret[ret.length] = ASN1.decode(stream);
865 if (stream.pos != end) {
866 throw new Error("Content size is not correct for container starting at offset " + start);
873 var s = ASN1.decode(stream);
879 len = start - stream.pos; // undefined lengths are represented as negative values
882 throw new Error("Exception while decoding undefined length content: " + e);
887 if (tag.tagConstructed) {
888 // must have valid content
891 else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
892 // sometimes BitString and OctetString are used to encapsulate ASN.1
894 if (tag.tagNumber == 0x03) {
895 if (stream.get() != 0) {
896 throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
900 for (var i = 0; i < sub.length; ++i) {
901 if (sub[i].tag.isEOC()) {
902 throw new Error("EOC is not supposed to be actual content.");
907 // but silently ignore when they don't
913 throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
915 stream.pos = start + Math.abs(len);
917 return new ASN1(streamStart, header, len, tag, sub);
921 var ASN1Tag = /** @class */ (function () {
922 function ASN1Tag(stream) {
923 var buf = stream.get();
924 this.tagClass = buf >> 6;
925 this.tagConstructed = ((buf & 0x20) !== 0);
926 this.tagNumber = buf & 0x1F;
927 if (this.tagNumber == 0x1F) { // long tag
931 n.mulAdd(128, buf & 0x7F);
932 } while (buf & 0x80);
933 this.tagNumber = n.simplify();
936 ASN1Tag.prototype.isUniversal = function () {
937 return this.tagClass === 0x00;
939 ASN1Tag.prototype.isEOC = function () {
940 return this.tagClass === 0x00 && this.tagNumber === 0x00;
945 // Copyright (c) 2005 Tom Wu
948 // JavaScript engine analysis
949 var canary = 0xdeadbeefcafe;
950 var j_lm = ((canary & 0xffffff) == 0xefcafe);
952 var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
953 var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
955 // (public) Constructor
956 var BigInteger = /** @class */ (function () {
957 function BigInteger(a, b, c) {
959 if ("number" == typeof a) {
960 this.fromNumber(a, b, c);
962 else if (b == null && "string" != typeof a) {
963 this.fromString(a, 256);
966 this.fromString(a, b);
971 // BigInteger.prototype.toString = bnToString;
972 // (public) return string representation in given radix
973 BigInteger.prototype.toString = function (b) {
975 return "-" + this.negate().toString(b);
994 return this.toRadix(b);
996 var km = (1 << k) - 1;
1001 var p = this.DB - (i * this.DB) % k;
1003 if (p < this.DB && (d = this[i] >> p) > 0) {
1009 d = (this[i] & ((1 << p) - 1)) << (k - p);
1010 d |= this[--i] >> (p += this.DB - k);
1013 d = (this[i] >> (p -= k)) & km;
1029 // BigInteger.prototype.negate = bnNegate;
1031 BigInteger.prototype.negate = function () {
1033 BigInteger.ZERO.subTo(this, r);
1036 // BigInteger.prototype.abs = bnAbs;
1038 BigInteger.prototype.abs = function () {
1039 return (this.s < 0) ? this.negate() : this;
1041 // BigInteger.prototype.compareTo = bnCompareTo;
1042 // (public) return + if this > a, - if this < a, 0 if equal
1043 BigInteger.prototype.compareTo = function (a) {
1044 var r = this.s - a.s;
1051 return (this.s < 0) ? -r : r;
1054 if ((r = this[i] - a[i]) != 0) {
1060 // BigInteger.prototype.bitLength = bnBitLength;
1061 // (public) return the number of bits in "this"
1062 BigInteger.prototype.bitLength = function () {
1066 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
1068 // BigInteger.prototype.mod = bnMod;
1069 // (public) this mod a
1070 BigInteger.prototype.mod = function (a) {
1072 this.abs().divRemTo(a, null, r);
1073 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
1078 // BigInteger.prototype.modPowInt = bnModPowInt;
1079 // (public) this^e % m, 0 <= e < 2^32
1080 BigInteger.prototype.modPowInt = function (e, m) {
1082 if (e < 256 || m.isEven()) {
1086 z = new Montgomery(m);
1088 return this.exp(e, z);
1090 // BigInteger.prototype.clone = bnClone;
1092 BigInteger.prototype.clone = function () {
1097 // BigInteger.prototype.intValue = bnIntValue;
1098 // (public) return value as integer
1099 BigInteger.prototype.intValue = function () {
1102 return this[0] - this.DV;
1104 else if (this.t == 0) {
1108 else if (this.t == 1) {
1111 else if (this.t == 0) {
1114 // assumes 16 < DB < 32
1115 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
1117 // BigInteger.prototype.byteValue = bnByteValue;
1118 // (public) return value as byte
1119 BigInteger.prototype.byteValue = function () {
1120 return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
1122 // BigInteger.prototype.shortValue = bnShortValue;
1123 // (public) return value as short (assumes DB>=16)
1124 BigInteger.prototype.shortValue = function () {
1125 return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
1127 // BigInteger.prototype.signum = bnSigNum;
1128 // (public) 0 if this == 0, 1 if this > 0
1129 BigInteger.prototype.signum = function () {
1133 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
1140 // BigInteger.prototype.toByteArray = bnToByteArray;
1141 // (public) convert to bigendian byte array
1142 BigInteger.prototype.toByteArray = function () {
1146 var p = this.DB - (i * this.DB) % 8;
1150 if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
1151 r[k++] = d | (this.s << (this.DB - p));
1155 d = (this[i] & ((1 << p) - 1)) << (8 - p);
1156 d |= this[--i] >> (p += this.DB - 8);
1159 d = (this[i] >> (p -= 8)) & 0xff;
1165 if ((d & 0x80) != 0) {
1168 if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
1171 if (k > 0 || d != this.s) {
1178 // BigInteger.prototype.equals = bnEquals;
1179 BigInteger.prototype.equals = function (a) {
1180 return (this.compareTo(a) == 0);
1182 // BigInteger.prototype.min = bnMin;
1183 BigInteger.prototype.min = function (a) {
1184 return (this.compareTo(a) < 0) ? this : a;
1186 // BigInteger.prototype.max = bnMax;
1187 BigInteger.prototype.max = function (a) {
1188 return (this.compareTo(a) > 0) ? this : a;
1190 // BigInteger.prototype.and = bnAnd;
1191 BigInteger.prototype.and = function (a) {
1193 this.bitwiseTo(a, op_and, r);
1196 // BigInteger.prototype.or = bnOr;
1197 BigInteger.prototype.or = function (a) {
1199 this.bitwiseTo(a, op_or, r);
1202 // BigInteger.prototype.xor = bnXor;
1203 BigInteger.prototype.xor = function (a) {
1205 this.bitwiseTo(a, op_xor, r);
1208 // BigInteger.prototype.andNot = bnAndNot;
1209 BigInteger.prototype.andNot = function (a) {
1211 this.bitwiseTo(a, op_andnot, r);
1214 // BigInteger.prototype.not = bnNot;
1216 BigInteger.prototype.not = function () {
1218 for (var i = 0; i < this.t; ++i) {
1219 r[i] = this.DM & ~this[i];
1225 // BigInteger.prototype.shiftLeft = bnShiftLeft;
1226 // (public) this << n
1227 BigInteger.prototype.shiftLeft = function (n) {
1230 this.rShiftTo(-n, r);
1233 this.lShiftTo(n, r);
1237 // BigInteger.prototype.shiftRight = bnShiftRight;
1238 // (public) this >> n
1239 BigInteger.prototype.shiftRight = function (n) {
1242 this.lShiftTo(-n, r);
1245 this.rShiftTo(n, r);
1249 // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
1250 // (public) returns index of lowest 1-bit (or -1 if none)
1251 BigInteger.prototype.getLowestSetBit = function () {
1252 for (var i = 0; i < this.t; ++i) {
1254 return i * this.DB + lbit(this[i]);
1258 return this.t * this.DB;
1262 // BigInteger.prototype.bitCount = bnBitCount;
1263 // (public) return number of set bits
1264 BigInteger.prototype.bitCount = function () {
1266 var x = this.s & this.DM;
1267 for (var i = 0; i < this.t; ++i) {
1268 r += cbit(this[i] ^ x);
1272 // BigInteger.prototype.testBit = bnTestBit;
1273 // (public) true iff nth bit is set
1274 BigInteger.prototype.testBit = function (n) {
1275 var j = Math.floor(n / this.DB);
1277 return (this.s != 0);
1279 return ((this[j] & (1 << (n % this.DB))) != 0);
1281 // BigInteger.prototype.setBit = bnSetBit;
1282 // (public) this | (1<<n)
1283 BigInteger.prototype.setBit = function (n) {
1284 return this.changeBit(n, op_or);
1286 // BigInteger.prototype.clearBit = bnClearBit;
1287 // (public) this & ~(1<<n)
1288 BigInteger.prototype.clearBit = function (n) {
1289 return this.changeBit(n, op_andnot);
1291 // BigInteger.prototype.flipBit = bnFlipBit;
1292 // (public) this ^ (1<<n)
1293 BigInteger.prototype.flipBit = function (n) {
1294 return this.changeBit(n, op_xor);
1296 // BigInteger.prototype.add = bnAdd;
1297 // (public) this + a
1298 BigInteger.prototype.add = function (a) {
1303 // BigInteger.prototype.subtract = bnSubtract;
1304 // (public) this - a
1305 BigInteger.prototype.subtract = function (a) {
1310 // BigInteger.prototype.multiply = bnMultiply;
1311 // (public) this * a
1312 BigInteger.prototype.multiply = function (a) {
1314 this.multiplyTo(a, r);
1317 // BigInteger.prototype.divide = bnDivide;
1318 // (public) this / a
1319 BigInteger.prototype.divide = function (a) {
1321 this.divRemTo(a, r, null);
1324 // BigInteger.prototype.remainder = bnRemainder;
1325 // (public) this % a
1326 BigInteger.prototype.remainder = function (a) {
1328 this.divRemTo(a, null, r);
1331 // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
1332 // (public) [this/a,this%a]
1333 BigInteger.prototype.divideAndRemainder = function (a) {
1336 this.divRemTo(a, q, r);
1339 // BigInteger.prototype.modPow = bnModPow;
1340 // (public) this^e % m (HAC 14.85)
1341 BigInteger.prototype.modPow = function (e, m) {
1342 var i = e.bitLength();
1367 else if (m.isEven()) {
1371 z = new Montgomery(m);
1377 var km = (1 << k) - 1;
1378 g[1] = z.convert(this);
1384 z.mulTo(g2, g[n - 2], g[n]);
1393 i = nbits(e[j]) - 1;
1396 w = (e[j] >> (i - k1)) & km;
1399 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
1401 w |= e[j - 1] >> (this.DB + i - k1);
1405 while ((w & 1) == 0) {
1413 if (is1) { // ret == 1, don't bother squaring or multiplying it
1431 z.mulTo(r2, g[w], r);
1433 while (j >= 0 && (e[j] & (1 << i)) == 0) {
1446 // BigInteger.prototype.modInverse = bnModInverse;
1447 // (public) 1/this % m (HAC 14.61)
1448 BigInteger.prototype.modInverse = function (m) {
1449 var ac = m.isEven();
1450 if ((this.isEven() && ac) || m.signum() == 0) {
1451 return BigInteger.ZERO;
1454 var v = this.clone();
1459 while (u.signum() != 0) {
1460 while (u.isEven()) {
1463 if (!a.isEven() || !b.isEven()) {
1469 else if (!b.isEven()) {
1474 while (v.isEven()) {
1477 if (!c.isEven() || !d.isEven()) {
1483 else if (!d.isEven()) {
1488 if (u.compareTo(v) >= 0) {
1503 if (v.compareTo(BigInteger.ONE) != 0) {
1504 return BigInteger.ZERO;
1506 if (d.compareTo(m) >= 0) {
1507 return d.subtract(m);
1509 if (d.signum() < 0) {
1515 if (d.signum() < 0) {
1522 // BigInteger.prototype.pow = bnPow;
1524 BigInteger.prototype.pow = function (e) {
1525 return this.exp(e, new NullExp());
1527 // BigInteger.prototype.gcd = bnGCD;
1528 // (public) gcd(this,a) (HAC 14.54)
1529 BigInteger.prototype.gcd = function (a) {
1530 var x = (this.s < 0) ? this.negate() : this.clone();
1531 var y = (a.s < 0) ? a.negate() : a.clone();
1532 if (x.compareTo(y) < 0) {
1537 var i = x.getLowestSetBit();
1538 var g = y.getLowestSetBit();
1549 while (x.signum() > 0) {
1550 if ((i = x.getLowestSetBit()) > 0) {
1553 if ((i = y.getLowestSetBit()) > 0) {
1556 if (x.compareTo(y) >= 0) {
1570 // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
1571 // (public) test primality with certainty >= 1-.5^t
1572 BigInteger.prototype.isProbablePrime = function (t) {
1575 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
1576 for (i = 0; i < lowprimes.length; ++i) {
1577 if (x[0] == lowprimes[i]) {
1587 while (i < lowprimes.length) {
1588 var m = lowprimes[i];
1590 while (j < lowprimes.length && m < lplim) {
1591 m *= lowprimes[j++];
1595 if (m % lowprimes[i++] == 0) {
1600 return x.millerRabin(t);
1604 // BigInteger.prototype.copyTo = bnpCopyTo;
1605 // (protected) copy this to r
1606 BigInteger.prototype.copyTo = function (r) {
1607 for (var i = this.t - 1; i >= 0; --i) {
1613 // BigInteger.prototype.fromInt = bnpFromInt;
1614 // (protected) set from integer value x, -DV <= x < DV
1615 BigInteger.prototype.fromInt = function (x) {
1617 this.s = (x < 0) ? -1 : 0;
1622 this[0] = x + this.DV;
1628 // BigInteger.prototype.fromString = bnpFromString;
1629 // (protected) set from string and radix
1630 BigInteger.prototype.fromString = function (s, b) {
1638 else if (b == 256) {
1652 this.fromRadix(s, b);
1661 var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
1663 if (s.charAt(i) == "-") {
1672 else if (sh + k > this.DB) {
1673 this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
1674 this[this.t++] = (x >> (this.DB - sh));
1677 this[this.t - 1] |= x << sh;
1680 if (sh >= this.DB) {
1684 if (k == 8 && ((+s[0]) & 0x80) != 0) {
1687 this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
1692 BigInteger.ZERO.subTo(this, this);
1695 // BigInteger.prototype.clamp = bnpClamp;
1696 // (protected) clamp off excess high words
1697 BigInteger.prototype.clamp = function () {
1698 var c = this.s & this.DM;
1699 while (this.t > 0 && this[this.t - 1] == c) {
1703 // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
1704 // (protected) r = this << n*DB
1705 BigInteger.prototype.dlShiftTo = function (n, r) {
1707 for (i = this.t - 1; i >= 0; --i) {
1710 for (i = n - 1; i >= 0; --i) {
1716 // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
1717 // (protected) r = this >> n*DB
1718 BigInteger.prototype.drShiftTo = function (n, r) {
1719 for (var i = n; i < this.t; ++i) {
1722 r.t = Math.max(this.t - n, 0);
1725 // BigInteger.prototype.lShiftTo = bnpLShiftTo;
1726 // (protected) r = this << n
1727 BigInteger.prototype.lShiftTo = function (n, r) {
1728 var bs = n % this.DB;
1729 var cbs = this.DB - bs;
1730 var bm = (1 << cbs) - 1;
1731 var ds = Math.floor(n / this.DB);
1732 var c = (this.s << bs) & this.DM;
1733 for (var i = this.t - 1; i >= 0; --i) {
1734 r[i + ds + 1] = (this[i] >> cbs) | c;
1735 c = (this[i] & bm) << bs;
1737 for (var i = ds - 1; i >= 0; --i) {
1741 r.t = this.t + ds + 1;
1745 // BigInteger.prototype.rShiftTo = bnpRShiftTo;
1746 // (protected) r = this >> n
1747 BigInteger.prototype.rShiftTo = function (n, r) {
1749 var ds = Math.floor(n / this.DB);
1754 var bs = n % this.DB;
1755 var cbs = this.DB - bs;
1756 var bm = (1 << bs) - 1;
1757 r[0] = this[ds] >> bs;
1758 for (var i = ds + 1; i < this.t; ++i) {
1759 r[i - ds - 1] |= (this[i] & bm) << cbs;
1760 r[i - ds] = this[i] >> bs;
1763 r[this.t - ds - 1] |= (this.s & bm) << cbs;
1768 // BigInteger.prototype.subTo = bnpSubTo;
1769 // (protected) r = this - a
1770 BigInteger.prototype.subTo = function (a, r) {
1773 var m = Math.min(a.t, this.t);
1775 c += this[i] - a[i];
1776 r[i++] = c & this.DM;
1781 while (i < this.t) {
1783 r[i++] = c & this.DM;
1792 r[i++] = c & this.DM;
1797 r.s = (c < 0) ? -1 : 0;
1799 r[i++] = this.DV + c;
1807 // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
1808 // (protected) r = this * a, r != this,a (HAC 14.12)
1809 // "this" should be the larger one if appropriate.
1810 BigInteger.prototype.multiplyTo = function (a, r) {
1818 for (i = 0; i < y.t; ++i) {
1819 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
1823 if (this.s != a.s) {
1824 BigInteger.ZERO.subTo(r, r);
1827 // BigInteger.prototype.squareTo = bnpSquareTo;
1828 // (protected) r = this^2, r != this (HAC 14.16)
1829 BigInteger.prototype.squareTo = function (r) {
1831 var i = r.t = 2 * x.t;
1835 for (i = 0; i < x.t - 1; ++i) {
1836 var c = x.am(i, x[i], r, 2 * i, 0, 1);
1837 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
1843 r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
1848 // BigInteger.prototype.divRemTo = bnpDivRemTo;
1849 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
1850 // r != q, this != m. q or r may be null.
1851 BigInteger.prototype.divRemTo = function (m, q, r) {
1856 var pt = this.abs();
1872 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
1874 pm.lShiftTo(nsh, y);
1875 pt.lShiftTo(nsh, r);
1886 var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
1887 var d1 = this.FV / yt;
1888 var d2 = (1 << this.F1) / yt;
1889 var e = 1 << this.F2;
1892 var t = (q == null) ? nbi() : q;
1894 if (r.compareTo(t) >= 0) {
1898 BigInteger.ONE.dlShiftTo(ys, t);
1899 t.subTo(y, y); // "negative" y so we can replace sub with am later
1904 // Estimate quotient digit
1905 var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
1906 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
1909 while (r[i] < --qd) {
1917 BigInteger.ZERO.subTo(q, q);
1924 } // Denormalize remainder
1926 BigInteger.ZERO.subTo(r, r);
1929 // BigInteger.prototype.invDigit = bnpInvDigit;
1930 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
1934 // xy(2-xy) = (1+km)(1-km)
1935 // x[y(2-xy)] = 1-k^2m^2
1936 // x[y(2-xy)] == 1 (mod m^2)
1937 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
1938 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
1939 // JS multiply "overflows" differently from C/C++, so care is needed here.
1940 BigInteger.prototype.invDigit = function () {
1948 var y = x & 3; // y == 1/x mod 2^2
1949 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
1950 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
1951 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
1952 // last step - calculate inverse mod DV directly;
1953 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
1954 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
1955 // we really want the negative inverse, and -DV < y < DV
1956 return (y > 0) ? this.DV - y : -y;
1958 // BigInteger.prototype.isEven = bnpIsEven;
1959 // (protected) true iff this is even
1960 BigInteger.prototype.isEven = function () {
1961 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
1963 // BigInteger.prototype.exp = bnpExp;
1964 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
1965 BigInteger.prototype.exp = function (e, z) {
1966 if (e > 0xffffffff || e < 1) {
1967 return BigInteger.ONE;
1971 var g = z.convert(this);
1972 var i = nbits(e) - 1;
1976 if ((e & (1 << i)) > 0) {
1987 // BigInteger.prototype.chunkSize = bnpChunkSize;
1988 // (protected) return x s.t. r^x < DV
1989 BigInteger.prototype.chunkSize = function (r) {
1990 return Math.floor(Math.LN2 * this.DB / Math.log(r));
1992 // BigInteger.prototype.toRadix = bnpToRadix;
1993 // (protected) convert to radix string
1994 BigInteger.prototype.toRadix = function (b) {
1998 if (this.signum() == 0 || b < 2 || b > 36) {
2001 var cs = this.chunkSize(b);
2002 var a = Math.pow(b, cs);
2007 this.divRemTo(d, y, z);
2008 while (y.signum() > 0) {
2009 r = (a + z.intValue()).toString(b).substr(1) + r;
2010 y.divRemTo(d, y, z);
2012 return z.intValue().toString(b) + r;
2014 // BigInteger.prototype.fromRadix = bnpFromRadix;
2015 // (protected) convert from radix string
2016 BigInteger.prototype.fromRadix = function (s, b) {
2021 var cs = this.chunkSize(b);
2022 var d = Math.pow(b, cs);
2026 for (var i = 0; i < s.length; ++i) {
2027 var x = intAt(s, i);
2029 if (s.charAt(i) == "-" && this.signum() == 0) {
2037 this.dAddOffset(w, 0);
2043 this.dMultiply(Math.pow(b, j));
2044 this.dAddOffset(w, 0);
2047 BigInteger.ZERO.subTo(this, this);
2050 // BigInteger.prototype.fromNumber = bnpFromNumber;
2051 // (protected) alternate constructor
2052 BigInteger.prototype.fromNumber = function (a, b, c) {
2053 if ("number" == typeof b) {
2054 // new BigInteger(int,int,RNG)
2059 this.fromNumber(a, c);
2060 if (!this.testBit(a - 1)) {
2062 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2064 if (this.isEven()) {
2065 this.dAddOffset(1, 0);
2067 while (!this.isProbablePrime(b)) {
2068 this.dAddOffset(2, 0);
2069 if (this.bitLength() > a) {
2070 this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
2076 // new BigInteger(int,RNG)
2079 x.length = (a >> 3) + 1;
2082 x[0] &= ((1 << t) - 1);
2087 this.fromString(x, 256);
2090 // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
2091 // (protected) r = this op a (bitwise)
2092 BigInteger.prototype.bitwiseTo = function (a, op, r) {
2095 var m = Math.min(a.t, this.t);
2096 for (i = 0; i < m; ++i) {
2097 r[i] = op(this[i], a[i]);
2101 for (i = m; i < this.t; ++i) {
2102 r[i] = op(this[i], f);
2107 f = this.s & this.DM;
2108 for (i = m; i < a.t; ++i) {
2113 r.s = op(this.s, a.s);
2116 // BigInteger.prototype.changeBit = bnpChangeBit;
2117 // (protected) this op (1<<n)
2118 BigInteger.prototype.changeBit = function (n, op) {
2119 var r = BigInteger.ONE.shiftLeft(n);
2120 this.bitwiseTo(r, op, r);
2123 // BigInteger.prototype.addTo = bnpAddTo;
2124 // (protected) r = this + a
2125 BigInteger.prototype.addTo = function (a, r) {
2128 var m = Math.min(a.t, this.t);
2130 c += this[i] + a[i];
2131 r[i++] = c & this.DM;
2136 while (i < this.t) {
2138 r[i++] = c & this.DM;
2147 r[i++] = c & this.DM;
2152 r.s = (c < 0) ? -1 : 0;
2157 r[i++] = this.DV + c;
2162 // BigInteger.prototype.dMultiply = bnpDMultiply;
2163 // (protected) this *= n, this >= 0, 1 < n < DV
2164 BigInteger.prototype.dMultiply = function (n) {
2165 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
2169 // BigInteger.prototype.dAddOffset = bnpDAddOffset;
2170 // (protected) this += n << w words, this >= 0
2171 BigInteger.prototype.dAddOffset = function (n, w) {
2175 while (this.t <= w) {
2179 while (this[w] >= this.DV) {
2181 if (++w >= this.t) {
2187 // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
2188 // (protected) r = lower n words of "this * a", a.t <= n
2189 // "this" should be the larger one if appropriate.
2190 BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
2191 var i = Math.min(this.t + a.t, n);
2192 r.s = 0; // assumes a,this >= 0
2197 for (var j = r.t - this.t; i < j; ++i) {
2198 r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
2200 for (var j = Math.min(a.t, n); i < j; ++i) {
2201 this.am(0, a[i], r, i, 0, n - i);
2205 // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
2206 // (protected) r = "this * a" without lower n words, n > 0
2207 // "this" should be the larger one if appropriate.
2208 BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
2210 var i = r.t = this.t + a.t - n;
2211 r.s = 0; // assumes a,this >= 0
2215 for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
2216 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
2221 // BigInteger.prototype.modInt = bnpModInt;
2222 // (protected) this % n, n < 2^26
2223 BigInteger.prototype.modInt = function (n) {
2227 var d = this.DV % n;
2228 var r = (this.s < 0) ? n - 1 : 0;
2234 for (var i = this.t - 1; i >= 0; --i) {
2235 r = (d * r + this[i]) % n;
2241 // BigInteger.prototype.millerRabin = bnpMillerRabin;
2242 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
2243 BigInteger.prototype.millerRabin = function (t) {
2244 var n1 = this.subtract(BigInteger.ONE);
2245 var k = n1.getLowestSetBit();
2249 var r = n1.shiftRight(k);
2251 if (t > lowprimes.length) {
2252 t = lowprimes.length;
2255 for (var i = 0; i < t; ++i) {
2256 // Pick bases at random, instead of starting at 2
2257 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
2258 var y = a.modPow(r, this);
2259 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
2261 while (j++ < k && y.compareTo(n1) != 0) {
2262 y = y.modPowInt(2, this);
2263 if (y.compareTo(BigInteger.ONE) == 0) {
2267 if (y.compareTo(n1) != 0) {
2274 // BigInteger.prototype.square = bnSquare;
2276 BigInteger.prototype.square = function () {
2282 // Public API method
2283 BigInteger.prototype.gcda = function (a, callback) {
2284 var x = (this.s < 0) ? this.negate() : this.clone();
2285 var y = (a.s < 0) ? a.negate() : a.clone();
2286 if (x.compareTo(y) < 0) {
2291 var i = x.getLowestSetBit();
2292 var g = y.getLowestSetBit();
2304 // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
2305 var gcda1 = function () {
2306 if ((i = x.getLowestSetBit()) > 0) {
2309 if ((i = y.getLowestSetBit()) > 0) {
2312 if (x.compareTo(y) >= 0) {
2320 if (!(x.signum() > 0)) {
2324 setTimeout(function () { callback(y); }, 0); // escape
2327 setTimeout(gcda1, 0);
2330 setTimeout(gcda1, 10);
2332 // (protected) alternate constructor
2333 BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
2334 if ("number" == typeof b) {
2339 this.fromNumber(a, c);
2340 if (!this.testBit(a - 1)) {
2341 this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
2343 if (this.isEven()) {
2344 this.dAddOffset(1, 0);
2347 var bnpfn1_1 = function () {
2348 bnp_1.dAddOffset(2, 0);
2349 if (bnp_1.bitLength() > a) {
2350 bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
2352 if (bnp_1.isProbablePrime(b)) {
2353 setTimeout(function () { callback(); }, 0); // escape
2356 setTimeout(bnpfn1_1, 0);
2359 setTimeout(bnpfn1_1, 0);
2365 x.length = (a >> 3) + 1;
2368 x[0] &= ((1 << t) - 1);
2373 this.fromString(x, 256);
2380 var NullExp = /** @class */ (function () {
2381 function NullExp() {
2383 // NullExp.prototype.convert = nNop;
2384 NullExp.prototype.convert = function (x) {
2387 // NullExp.prototype.revert = nNop;
2388 NullExp.prototype.revert = function (x) {
2391 // NullExp.prototype.mulTo = nMulTo;
2392 NullExp.prototype.mulTo = function (x, y, r) {
2395 // NullExp.prototype.sqrTo = nSqrTo;
2396 NullExp.prototype.sqrTo = function (x, r) {
2401 // Modular reduction using "classic" algorithm
2402 var Classic = /** @class */ (function () {
2403 function Classic(m) {
2406 // Classic.prototype.convert = cConvert;
2407 Classic.prototype.convert = function (x) {
2408 if (x.s < 0 || x.compareTo(this.m) >= 0) {
2409 return x.mod(this.m);
2415 // Classic.prototype.revert = cRevert;
2416 Classic.prototype.revert = function (x) {
2419 // Classic.prototype.reduce = cReduce;
2420 Classic.prototype.reduce = function (x) {
2421 x.divRemTo(this.m, null, x);
2423 // Classic.prototype.mulTo = cMulTo;
2424 Classic.prototype.mulTo = function (x, y, r) {
2428 // Classic.prototype.sqrTo = cSqrTo;
2429 Classic.prototype.sqrTo = function (x, r) {
2436 //#region Montgomery
2437 // Montgomery reduction
2438 var Montgomery = /** @class */ (function () {
2439 function Montgomery(m) {
2441 this.mp = m.invDigit();
2442 this.mpl = this.mp & 0x7fff;
2443 this.mph = this.mp >> 15;
2444 this.um = (1 << (m.DB - 15)) - 1;
2447 // Montgomery.prototype.convert = montConvert;
2449 Montgomery.prototype.convert = function (x) {
2451 x.abs().dlShiftTo(this.m.t, r);
2452 r.divRemTo(this.m, null, r);
2453 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
2458 // Montgomery.prototype.revert = montRevert;
2460 Montgomery.prototype.revert = function (x) {
2466 // Montgomery.prototype.reduce = montReduce;
2467 // x = x/R mod m (HAC 14.32)
2468 Montgomery.prototype.reduce = function (x) {
2469 while (x.t <= this.mt2) {
2470 // pad x so am has enough room later
2473 for (var i = 0; i < this.m.t; ++i) {
2474 // faster way of calculating u0 = x[i]*mp mod DV
2475 var j = x[i] & 0x7fff;
2476 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
2477 // use am to combine the multiply-shift-add into one call
2479 x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
2481 while (x[j] >= x.DV) {
2487 x.drShiftTo(this.m.t, x);
2488 if (x.compareTo(this.m) >= 0) {
2492 // Montgomery.prototype.mulTo = montMulTo;
2493 // r = "xy/R mod m"; x,y != r
2494 Montgomery.prototype.mulTo = function (x, y, r) {
2498 // Montgomery.prototype.sqrTo = montSqrTo;
2499 // r = "x^2/R mod m"; x != r
2500 Montgomery.prototype.sqrTo = function (x, r) {
2506 //#endregion Montgomery
2508 // Barrett modular reduction
2509 var Barrett = /** @class */ (function () {
2510 function Barrett(m) {
2515 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
2516 this.mu = this.r2.divide(m);
2518 // Barrett.prototype.convert = barrettConvert;
2519 Barrett.prototype.convert = function (x) {
2520 if (x.s < 0 || x.t > 2 * this.m.t) {
2521 return x.mod(this.m);
2523 else if (x.compareTo(this.m) < 0) {
2533 // Barrett.prototype.revert = barrettRevert;
2534 Barrett.prototype.revert = function (x) {
2537 // Barrett.prototype.reduce = barrettReduce;
2538 // x = x mod m (HAC 14.42)
2539 Barrett.prototype.reduce = function (x) {
2540 x.drShiftTo(this.m.t - 1, this.r2);
2541 if (x.t > this.m.t + 1) {
2545 this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
2546 this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
2547 while (x.compareTo(this.r2) < 0) {
2548 x.dAddOffset(1, this.m.t + 1);
2550 x.subTo(this.r2, x);
2551 while (x.compareTo(this.m) >= 0) {
2555 // Barrett.prototype.mulTo = barrettMulTo;
2556 // r = x*y mod m; x,y != r
2557 Barrett.prototype.mulTo = function (x, y, r) {
2561 // Barrett.prototype.sqrTo = barrettSqrTo;
2562 // r = x^2 mod m; x != r
2563 Barrett.prototype.sqrTo = function (x, r) {
2570 //#endregion REDUCERS
2571 // return new, unset BigInteger
2572 function nbi() { return new BigInteger(null); }
2573 function parseBigInt(str, r) {
2574 return new BigInteger(str, r);
2576 // am: Compute w_j += (x*this_i), propagate carries,
2577 // c is initial carry, returns final carry.
2578 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
2579 // We need to select the fastest one that works in this environment.
2580 // am1: use a single mult and divide to get the high bits,
2581 // max digit bits should be 26 because
2582 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
2583 function am1(i, x, w, j, c, n) {
2585 var v = x * this[i++] + w[j] + c;
2586 c = Math.floor(v / 0x4000000);
2587 w[j++] = v & 0x3ffffff;
2591 // am2 avoids a big mult-and-extract completely.
2592 // Max digit bits should be <= 30 because we do bitwise ops
2593 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
2594 function am2(i, x, w, j, c, n) {
2595 var xl = x & 0x7fff;
2598 var l = this[i] & 0x7fff;
2599 var h = this[i++] >> 15;
2600 var m = xh * l + h * xl;
2601 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
2602 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
2603 w[j++] = l & 0x3fffffff;
2607 // Alternately, set max digit bits to 28 since some
2608 // browsers slow down when dealing with 32-bit numbers.
2609 function am3(i, x, w, j, c, n) {
2610 var xl = x & 0x3fff;
2613 var l = this[i] & 0x3fff;
2614 var h = this[i++] >> 14;
2615 var m = xh * l + h * xl;
2616 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
2617 c = (l >> 28) + (m >> 14) + xh * h;
2618 w[j++] = l & 0xfffffff;
2622 // if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
2623 // BigInteger.prototype.am = am2;
2626 // else if (j_lm && (navigator.appName != "Netscape")) {
2627 // BigInteger.prototype.am = am1;
2630 // else { // Mozilla/Netscape seems to prefer am3
2631 // BigInteger.prototype.am = am3;
2634 BigInteger.prototype.am = am1;
2637 BigInteger.prototype.DB = dbits;
2638 BigInteger.prototype.DM = ((1 << dbits) - 1);
2639 BigInteger.prototype.DV = (1 << dbits);
2641 BigInteger.prototype.FV = Math.pow(2, BI_FP);
2642 BigInteger.prototype.F1 = BI_FP - dbits;
2643 BigInteger.prototype.F2 = 2 * dbits - BI_FP;
2644 // Digit conversions
2648 rr = "0".charCodeAt(0);
2649 for (vv = 0; vv <= 9; ++vv) {
2652 rr = "a".charCodeAt(0);
2653 for (vv = 10; vv < 36; ++vv) {
2656 rr = "A".charCodeAt(0);
2657 for (vv = 10; vv < 36; ++vv) {
2660 function intAt(s, i) {
2661 var c = BI_RC[s.charCodeAt(i)];
2662 return (c == null) ? -1 : c;
2664 // return bigint initialized to value
2670 // returns bit length of the integer x
2674 if ((t = x >>> 16) != 0) {
2678 if ((t = x >> 8) != 0) {
2682 if ((t = x >> 4) != 0) {
2686 if ((t = x >> 2) != 0) {
2690 if ((t = x >> 1) != 0) {
2697 BigInteger.ZERO = nbv(0);
2698 BigInteger.ONE = nbv(1);
2700 // prng4.js - uses Arcfour as a PRNG
2701 var Arcfour = /** @class */ (function () {
2702 function Arcfour() {
2707 // Arcfour.prototype.init = ARC4init;
2708 // Initialize arcfour context from key, an array of ints, each from [0..255]
2709 Arcfour.prototype.init = function (key) {
2713 for (i = 0; i < 256; ++i) {
2717 for (i = 0; i < 256; ++i) {
2718 j = (j + this.S[i] + key[i % key.length]) & 255;
2720 this.S[i] = this.S[j];
2726 // Arcfour.prototype.next = ARC4next;
2727 Arcfour.prototype.next = function () {
2729 this.i = (this.i + 1) & 255;
2730 this.j = (this.j + this.S[this.i]) & 255;
2732 this.S[this.i] = this.S[this.j];
2734 return this.S[(t + this.S[this.i]) & 255];
2738 // Plug in your RNG constructor here
2739 function prng_newstate() {
2740 return new Arcfour();
2742 // Pool size must be a multiple of 4 and greater than 32.
2743 // An array of bytes the size of the pool will be passed to init()
2744 var rng_psize = 256;
2746 // Random number generator - requires a PRNG backend, e.g. prng4.js
2748 var rng_pool = null;
2750 // Initialize the pool with junk if needed.
2751 if (rng_pool == null) {
2755 if (window.crypto && window.crypto.getRandomValues) {
2756 // Extract entropy (2048 bits) from RNG if available
2757 var z = new Uint32Array(256);
2758 window.crypto.getRandomValues(z);
2759 for (t = 0; t < z.length; ++t) {
2760 rng_pool[rng_pptr++] = z[t] & 255;
2763 // Use mouse events for entropy, if we do not have enough entropy by the time
2764 // we need it, entropy will be generated by Math.random.
2765 var onMouseMoveListener_1 = function (ev) {
2766 this.count = this.count || 0;
2767 if (this.count >= 256 || rng_pptr >= rng_psize) {
2768 if (window.removeEventListener) {
2769 window.removeEventListener("mousemove", onMouseMoveListener_1, false);
2771 else if (window.detachEvent) {
2772 window.detachEvent("onmousemove", onMouseMoveListener_1);
2777 var mouseCoordinates = ev.x + ev.y;
2778 rng_pool[rng_pptr++] = mouseCoordinates & 255;
2782 // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
2785 if (window.addEventListener) {
2786 window.addEventListener("mousemove", onMouseMoveListener_1, false);
2788 else if (window.attachEvent) {
2789 window.attachEvent("onmousemove", onMouseMoveListener_1);
2792 function rng_get_byte() {
2793 if (rng_state == null) {
2794 rng_state = prng_newstate();
2795 // At this point, we may not have collected enough entropy. If not, fall back to Math.random
2796 while (rng_pptr < rng_psize) {
2797 var random = Math.floor(65536 * Math.random());
2798 rng_pool[rng_pptr++] = random & 255;
2800 rng_state.init(rng_pool);
2801 for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
2802 rng_pool[rng_pptr] = 0;
2806 // TODO: allow reseeding after first request
2807 return rng_state.next();
2809 var SecureRandom = /** @class */ (function () {
2810 function SecureRandom() {
2812 SecureRandom.prototype.nextBytes = function (ba) {
2813 for (var i = 0; i < ba.length; ++i) {
2814 ba[i] = rng_get_byte();
2817 return SecureRandom;
2820 // Depends on jsbn.js and rng.js
2821 // function linebrk(s,n) {
2824 // while(i + n < s.length) {
2825 // ret += s.substring(i,i+n) + "\n";
2828 // return ret + s.substring(i,s.length);
2830 // function byte2Hex(b) {
2832 // return "0" + b.toString(16);
2834 // return b.toString(16);
2836 function pkcs1pad1(s, n) {
2837 if (n < s.length + 22) {
2838 console.error("Message too long for RSA");
2841 var len = n - s.length - 6;
2843 for (var f = 0; f < len; f += 2) {
2846 var m = "0001" + filler + "00" + s;
2847 return parseBigInt(m, 16);
2849 // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
2850 function pkcs1pad2(s, n) {
2851 if (n < s.length + 11) { // TODO: fix for utf-8
2852 console.error("Message too long for RSA");
2856 var i = s.length - 1;
2857 while (i >= 0 && n > 0) {
2858 var c = s.charCodeAt(i--);
2859 if (c < 128) { // encode using utf-8
2862 else if ((c > 127) && (c < 2048)) {
2863 ba[--n] = (c & 63) | 128;
2864 ba[--n] = (c >> 6) | 192;
2867 ba[--n] = (c & 63) | 128;
2868 ba[--n] = ((c >> 6) & 63) | 128;
2869 ba[--n] = (c >> 12) | 224;
2873 var rng = new SecureRandom();
2875 while (n > 2) { // random non-zero pad
2884 return new BigInteger(ba);
2886 // "empty" RSA key constructor
2887 var RSAKey = /** @class */ (function () {
2900 // RSAKey.prototype.doPublic = RSADoPublic;
2901 // Perform raw public operation on "x": return x^e (mod n)
2902 RSAKey.prototype.doPublic = function (x) {
2903 return x.modPowInt(this.e, this.n);
2905 // RSAKey.prototype.doPrivate = RSADoPrivate;
2906 // Perform raw private operation on "x": return x^d (mod n)
2907 RSAKey.prototype.doPrivate = function (x) {
2908 if (this.p == null || this.q == null) {
2909 return x.modPow(this.d, this.n);
2911 // TODO: re-calculate any missing CRT params
2912 var xp = x.mod(this.p).modPow(this.dmp1, this.p);
2913 var xq = x.mod(this.q).modPow(this.dmq1, this.q);
2914 while (xp.compareTo(xq) < 0) {
2915 xp = xp.add(this.p);
2917 return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
2919 //#endregion PROTECTED
2921 // RSAKey.prototype.setPublic = RSASetPublic;
2922 // Set the public key fields N and e from hex strings
2923 RSAKey.prototype.setPublic = function (N, E) {
2924 if (N != null && E != null && N.length > 0 && E.length > 0) {
2925 this.n = parseBigInt(N, 16);
2926 this.e = parseInt(E, 16);
2929 console.error("Invalid RSA public key");
2932 // RSAKey.prototype.encrypt = RSAEncrypt;
2933 // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
2934 RSAKey.prototype.encrypt = function (text) {
2935 var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
2939 var c = this.doPublic(m);
2943 var h = c.toString(16);
2944 if ((h.length & 1) == 0) {
2951 // RSAKey.prototype.setPrivate = RSASetPrivate;
2952 // Set the private key fields N, e, and d from hex strings
2953 RSAKey.prototype.setPrivate = function (N, E, D) {
2954 if (N != null && E != null && N.length > 0 && E.length > 0) {
2955 this.n = parseBigInt(N, 16);
2956 this.e = parseInt(E, 16);
2957 this.d = parseBigInt(D, 16);
2960 console.error("Invalid RSA private key");
2963 // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
2964 // Set the private key fields N, e, d and CRT params from hex strings
2965 RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
2966 if (N != null && E != null && N.length > 0 && E.length > 0) {
2967 this.n = parseBigInt(N, 16);
2968 this.e = parseInt(E, 16);
2969 this.d = parseBigInt(D, 16);
2970 this.p = parseBigInt(P, 16);
2971 this.q = parseBigInt(Q, 16);
2972 this.dmp1 = parseBigInt(DP, 16);
2973 this.dmq1 = parseBigInt(DQ, 16);
2974 this.coeff = parseBigInt(C, 16);
2977 console.error("Invalid RSA private key");
2980 // RSAKey.prototype.generate = RSAGenerate;
2981 // Generate a new random private key B bits long, using public expt E
2982 RSAKey.prototype.generate = function (B, E) {
2983 var rng = new SecureRandom();
2985 this.e = parseInt(E, 16);
2986 var ee = new BigInteger(E, 16);
2989 this.p = new BigInteger(B - qs, 1, rng);
2990 if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
2995 this.q = new BigInteger(qs, 1, rng);
2996 if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
3000 if (this.p.compareTo(this.q) <= 0) {
3005 var p1 = this.p.subtract(BigInteger.ONE);
3006 var q1 = this.q.subtract(BigInteger.ONE);
3007 var phi = p1.multiply(q1);
3008 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3009 this.n = this.p.multiply(this.q);
3010 this.d = ee.modInverse(phi);
3011 this.dmp1 = this.d.mod(p1);
3012 this.dmq1 = this.d.mod(q1);
3013 this.coeff = this.q.modInverse(this.p);
3018 // RSAKey.prototype.decrypt = RSADecrypt;
3019 // Return the PKCS#1 RSA decryption of "ctext".
3020 // "ctext" is an even-length hex string and the output is a plain string.
3021 RSAKey.prototype.decrypt = function (ctext) {
3022 var c = parseBigInt(ctext, 16);
3023 var m = this.doPrivate(c);
3027 return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
3029 // Generate a new random private key B bits long, using public expt E
3030 RSAKey.prototype.generateAsync = function (B, E, callback) {
3031 var rng = new SecureRandom();
3033 this.e = parseInt(E, 16);
3034 var ee = new BigInteger(E, 16);
3036 // These functions have non-descript names because they were originally for(;;) loops.
3037 // I don't know about cryptography to give them better names than loop1-4.
3038 var loop1 = function () {
3039 var loop4 = function () {
3040 if (rsa.p.compareTo(rsa.q) <= 0) {
3045 var p1 = rsa.p.subtract(BigInteger.ONE);
3046 var q1 = rsa.q.subtract(BigInteger.ONE);
3047 var phi = p1.multiply(q1);
3048 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
3049 rsa.n = rsa.p.multiply(rsa.q);
3050 rsa.d = ee.modInverse(phi);
3051 rsa.dmp1 = rsa.d.mod(p1);
3052 rsa.dmq1 = rsa.d.mod(q1);
3053 rsa.coeff = rsa.q.modInverse(rsa.p);
3054 setTimeout(function () { callback(); }, 0); // escape
3057 setTimeout(loop1, 0);
3060 var loop3 = function () {
3062 rsa.q.fromNumberAsync(qs, 1, rng, function () {
3063 rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
3064 if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
3065 setTimeout(loop4, 0);
3068 setTimeout(loop3, 0);
3073 var loop2 = function () {
3075 rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
3076 rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
3077 if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
3078 setTimeout(loop3, 0);
3081 setTimeout(loop2, 0);
3086 setTimeout(loop2, 0);
3088 setTimeout(loop1, 0);
3090 RSAKey.prototype.sign = function (text, digestMethod, digestName) {
3091 var header = getDigestHeader(digestName);
3092 var digest = header + digestMethod(text).toString();
3093 var m = pkcs1pad1(digest, this.n.bitLength() / 4);
3097 var c = this.doPrivate(m);
3101 var h = c.toString(16);
3102 if ((h.length & 1) == 0) {
3109 RSAKey.prototype.verify = function (text, signature, digestMethod) {
3110 var c = parseBigInt(signature, 16);
3111 var m = this.doPublic(c);
3115 var unpadded = m.toString(16).replace(/^1f+00/, "");
3116 var digest = removeDigestHeader(unpadded);
3117 return digest == digestMethod(text).toString();
3121 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
3122 function pkcs1unpad2(d, n) {
3123 var b = d.toByteArray();
3125 while (i < b.length && b[i] == 0) {
3128 if (b.length - i != n - 1 || b[i] != 2) {
3133 if (++i >= b.length) {
3138 while (++i < b.length) {
3140 if (c < 128) { // utf-8 decode
3141 ret += String.fromCharCode(c);
3143 else if ((c > 191) && (c < 224)) {
3144 ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
3148 ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
3154 // https://tools.ietf.org/html/rfc3447#page-43
3155 var DIGEST_HEADERS = {
3156 md2: "3020300c06082a864886f70d020205000410",
3157 md5: "3020300c06082a864886f70d020505000410",
3158 sha1: "3021300906052b0e03021a05000414",
3159 sha224: "302d300d06096086480165030402040500041c",
3160 sha256: "3031300d060960864801650304020105000420",
3161 sha384: "3041300d060960864801650304020205000430",
3162 sha512: "3051300d060960864801650304020305000440",
3163 ripemd160: "3021300906052b2403020105000414",
3165 function getDigestHeader(name) {
3166 return DIGEST_HEADERS[name] || "";
3168 function removeDigestHeader(str) {
3169 for (var name_1 in DIGEST_HEADERS) {
3170 if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
3171 var header = DIGEST_HEADERS[name_1];
3172 var len = header.length;
3173 if (str.substr(0, len) == header) {
3174 return str.substr(len);
3180 // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
3181 // function RSAEncryptB64(text) {
3182 // var h = this.encrypt(text);
3183 // if(h) return hex2b64(h); else return null;
3186 // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
3189 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3190 Code licensed under the BSD License:
3191 http://developer.yahoo.com/yui/license.html
3197 * Utility to set up the prototype, constructor and superclass properties to
3198 * support an inheritance strategy that can chain constructors and methods.
3199 * Static members will not be inherited.
3203 * @param {Function} subc the object to modify
3204 * @param {Function} superc the object to inherit
3205 * @param {Object} overrides additional properties/methods to add to the
3206 * subclass prototype. These will override the
3207 * matching items obtained from the superclass
3210 extend: function(subc, superc, overrides) {
3211 if (! superc || ! subc) {
3212 throw new Error("YAHOO.lang.extend failed, please check that " +
3213 "all dependencies are included.");
3216 var F = function() {};
3217 F.prototype = superc.prototype;
3218 subc.prototype = new F();
3219 subc.prototype.constructor = subc;
3220 subc.superclass = superc.prototype;
3222 if (superc.prototype.constructor == Object.prototype.constructor) {
3223 superc.prototype.constructor = superc;
3228 for (i in overrides) {
3229 subc.prototype[i] = overrides[i];
3233 * IE will not enumerate native functions in a derived object even if the
3234 * function was overridden. This is a workaround for specific functions
3235 * we care about on the Object prototype.
3236 * @property _IEEnumFix
3237 * @param {Function} r the object to receive the augmentation
3238 * @param {Function} s the object that supplies the properties to augment
3242 var _IEEnumFix = function() {},
3243 ADD = ["toString", "valueOf"];
3245 if (/MSIE/.test(navigator.userAgent)) {
3246 _IEEnumFix = function(r, s) {
3247 for (i = 0; i < ADD.length; i = i + 1) {
3248 var fname = ADD[i], f = s[fname];
3249 if (typeof f === 'function' && f != Object.prototype[fname]) {
3255 } catch (ex) {} _IEEnumFix(subc.prototype, overrides);
3260 /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
3266 * @author Kenji Urushima kenji.urushima@gmail.com
3267 * @version asn1 1.0.13 (2017-Jun-02)
3268 * @since jsrsasign 2.1
3269 * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
3273 * kjur's class library name space
3275 * This name space provides following name spaces:
3277 * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
3278 * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
3279 * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
3280 * class and utilities</li>
3283 * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
3285 * @namespace kjur's class library name space
3290 * kjur's ASN.1 class library name space
3292 * This is ITU-T X.690 ASN.1 DER encoder class library and
3293 * class structure and methods is very similar to
3294 * org.bouncycastle.asn1 package of
3295 * well known BouncyCaslte Cryptography Library.
3296 * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
3297 * Here are ASN.1 DER primitive classes.
3299 * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
3300 * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
3301 * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
3302 * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
3303 * <li>0x05 {@link KJUR.asn1.DERNull}</li>
3304 * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
3305 * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
3306 * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
3307 * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
3308 * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
3309 * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
3310 * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
3311 * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
3312 * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
3313 * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
3314 * <li>0x31 {@link KJUR.asn1.DERSet}</li>
3316 * <h4>OTHER ASN.1 CLASSES</h4>
3318 * <li>{@link KJUR.asn1.ASN1Object}</li>
3319 * <li>{@link KJUR.asn1.DERAbstractString}</li>
3320 * <li>{@link KJUR.asn1.DERAbstractTime}</li>
3321 * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
3322 * <li>{@link KJUR.asn1.DERTaggedObject}</li>
3324 * <h4>SUB NAME SPACES</h4>
3326 * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
3327 * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
3328 * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
3329 * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
3330 * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
3333 * NOTE: Please ignore method summary and document of this namespace.
3334 * This caused by a bug of jsdoc2.
3338 if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
3341 * ASN1 utilities class
3342 * @name KJUR.asn1.ASN1Util
3343 * @class ASN1 utilities class
3346 KJUR.asn1.ASN1Util = new function() {
3347 this.integerToByteHex = function(i) {
3348 var h = i.toString(16);
3349 if ((h.length % 2) == 1) h = '0' + h;
3352 this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
3353 var h = bigIntegerValue.toString(16);
3354 if (h.substr(0, 1) != '-') {
3355 if (h.length % 2 == 1) {
3358 if (! h.match(/^[0-7]/)) {
3363 var hPos = h.substr(1);
3364 var xorLen = hPos.length;
3365 if (xorLen % 2 == 1) {
3368 if (! h.match(/^[0-7]/)) {
3373 for (var i = 0; i < xorLen; i++) {
3376 var biMask = new BigInteger(hMask, 16);
3377 var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
3378 h = biNeg.toString(16).replace(/^-/, '');
3383 * get PEM string from hexadecimal data and header string
3384 * @name getPEMStringFromHex
3385 * @memberOf KJUR.asn1.ASN1Util
3387 * @param {String} dataHex hexadecimal string of PEM body
3388 * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
3389 * @return {String} PEM formatted string of input data
3391 * This method converts a hexadecimal string to a PEM string with
3392 * a specified header. Its line break will be CRLF("\r\n").
3394 * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
3395 * // value of pem will be:
3396 * -----BEGIN PRIVATE KEY-----
3398 * -----END PRIVATE KEY-----
3400 this.getPEMStringFromHex = function(dataHex, pemHeader) {
3401 return hextopem(dataHex, pemHeader);
3405 * generate ASN1Object specifed by JSON parameters
3407 * @memberOf KJUR.asn1.ASN1Util
3409 * @param {Array} param JSON parameter to generate ASN1Object
3410 * @return {KJUR.asn1.ASN1Object} generated object
3413 * generate any ASN1Object specified by JSON param
3414 * including ASN.1 primitive or structured.
3415 * Generally 'param' can be described as follows:
3417 * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
3419 * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
3421 * <li>'bool' - DERBoolean</li>
3422 * <li>'int' - DERInteger</li>
3423 * <li>'bitstr' - DERBitString</li>
3424 * <li>'octstr' - DEROctetString</li>
3425 * <li>'null' - DERNull</li>
3426 * <li>'oid' - DERObjectIdentifier</li>
3427 * <li>'enum' - DEREnumerated</li>
3428 * <li>'utf8str' - DERUTF8String</li>
3429 * <li>'numstr' - DERNumericString</li>
3430 * <li>'prnstr' - DERPrintableString</li>
3431 * <li>'telstr' - DERTeletexString</li>
3432 * <li>'ia5str' - DERIA5String</li>
3433 * <li>'utctime' - DERUTCTime</li>
3434 * <li>'gentime' - DERGeneralizedTime</li>
3435 * <li>'seq' - DERSequence</li>
3436 * <li>'set' - DERSet</li>
3437 * <li>'tag' - DERTaggedObject</li>
3440 * newObject({'prnstr': 'aaa'});
3441 * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
3442 * // ASN.1 Tagged Object
3443 * newObject({'tag': {'tag': 'a1',
3445 * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
3446 * // more simple representation of ASN.1 Tagged Object
3447 * newObject({'tag': ['a1',
3451 * {'prnstr': 'aaa'}]}
3454 this.newObject = function(param) {
3456 _KJUR_asn1 = _KJUR.asn1,
3457 _DERBoolean = _KJUR_asn1.DERBoolean,
3458 _DERInteger = _KJUR_asn1.DERInteger,
3459 _DERBitString = _KJUR_asn1.DERBitString,
3460 _DEROctetString = _KJUR_asn1.DEROctetString,
3461 _DERNull = _KJUR_asn1.DERNull,
3462 _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
3463 _DEREnumerated = _KJUR_asn1.DEREnumerated,
3464 _DERUTF8String = _KJUR_asn1.DERUTF8String,
3465 _DERNumericString = _KJUR_asn1.DERNumericString,
3466 _DERPrintableString = _KJUR_asn1.DERPrintableString,
3467 _DERTeletexString = _KJUR_asn1.DERTeletexString,
3468 _DERIA5String = _KJUR_asn1.DERIA5String,
3469 _DERUTCTime = _KJUR_asn1.DERUTCTime,
3470 _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
3471 _DERSequence = _KJUR_asn1.DERSequence,
3472 _DERSet = _KJUR_asn1.DERSet,
3473 _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
3474 _newObject = _KJUR_asn1.ASN1Util.newObject;
3476 var keys = Object.keys(param);
3477 if (keys.length != 1)
3478 throw "key of param shall be only one.";
3481 if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
3482 throw "undefined key: " + key;
3484 if (key == "bool") return new _DERBoolean(param[key]);
3485 if (key == "int") return new _DERInteger(param[key]);
3486 if (key == "bitstr") return new _DERBitString(param[key]);
3487 if (key == "octstr") return new _DEROctetString(param[key]);
3488 if (key == "null") return new _DERNull(param[key]);
3489 if (key == "oid") return new _DERObjectIdentifier(param[key]);
3490 if (key == "enum") return new _DEREnumerated(param[key]);
3491 if (key == "utf8str") return new _DERUTF8String(param[key]);
3492 if (key == "numstr") return new _DERNumericString(param[key]);
3493 if (key == "prnstr") return new _DERPrintableString(param[key]);
3494 if (key == "telstr") return new _DERTeletexString(param[key]);
3495 if (key == "ia5str") return new _DERIA5String(param[key]);
3496 if (key == "utctime") return new _DERUTCTime(param[key]);
3497 if (key == "gentime") return new _DERGeneralizedTime(param[key]);
3500 var paramList = param[key];
3502 for (var i = 0; i < paramList.length; i++) {
3503 var asn1Obj = _newObject(paramList[i]);
3506 return new _DERSequence({'array': a});
3510 var paramList = param[key];
3512 for (var i = 0; i < paramList.length; i++) {
3513 var asn1Obj = _newObject(paramList[i]);
3516 return new _DERSet({'array': a});
3520 var tagParam = param[key];
3521 if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
3522 tagParam.length == 3) {
3523 var obj = _newObject(tagParam[2]);
3524 return new _DERTaggedObject({tag: tagParam[0],
3525 explicit: tagParam[1],
3529 if (tagParam.explicit !== undefined)
3530 newParam.explicit = tagParam.explicit;
3531 if (tagParam.tag !== undefined)
3532 newParam.tag = tagParam.tag;
3533 if (tagParam.obj === undefined)
3534 throw "obj shall be specified for 'tag'.";
3535 newParam.obj = _newObject(tagParam.obj);
3536 return new _DERTaggedObject(newParam);
3542 * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
3543 * @name jsonToASN1HEX
3544 * @memberOf KJUR.asn1.ASN1Util
3546 * @param {Array} param JSON parameter to generate ASN1Object
3547 * @return hexadecimal string of ASN1Object
3550 * As for ASN.1 object representation of JSON object,
3551 * please see {@link newObject}.
3553 * jsonToASN1HEX({'prnstr': 'aaa'});
3555 this.jsonToASN1HEX = function(param) {
3556 var asn1Obj = this.newObject(param);
3557 return asn1Obj.getEncodedHex();
3562 * get dot noted oid number string from hexadecimal value of OID
3564 * @memberOf KJUR.asn1.ASN1Util
3566 * @param {String} hex hexadecimal value of object identifier
3567 * @return {String} dot noted string of object identifier
3568 * @since jsrsasign 4.8.3 asn1 1.0.7
3570 * This static method converts from hexadecimal string representation of
3571 * ASN.1 value of object identifier to oid number string.
3573 * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6"
3575 KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
3577 var i01 = parseInt(hex.substr(0, 2), 16);
3578 var i0 = Math.floor(i01 / 40);
3580 var s = i0 + "." + i1;
3583 for (var i = 2; i < hex.length; i += 2) {
3584 var value = parseInt(hex.substr(i, 2), 16);
3585 var bin = ("00000000" + value.toString(2)).slice(- 8);
3586 binbuf = binbuf + bin.substr(1, 7);
3587 if (bin.substr(0, 1) == "0") {
3588 var bi = new BigInteger(binbuf, 2);
3589 s = s + "." + bi.toString(10);
3597 * get hexadecimal value of object identifier from dot noted oid value
3599 * @memberOf KJUR.asn1.ASN1Util
3601 * @param {String} oidString dot noted string of object identifier
3602 * @return {String} hexadecimal value of object identifier
3603 * @since jsrsasign 4.8.3 asn1 1.0.7
3605 * This static method converts from object identifier value string.
3606 * to hexadecimal string representation of it.
3608 * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406"
3610 KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
3611 var itox = function(i) {
3612 var h = i.toString(16);
3613 if (h.length == 1) h = '0' + h;
3617 var roidtox = function(roid) {
3619 var bi = new BigInteger(roid, 10);
3620 var b = bi.toString(2);
3621 var padLen = 7 - b.length % 7;
3622 if (padLen == 7) padLen = 0;
3624 for (var i = 0; i < padLen; i++) bPad += '0';
3626 for (var i = 0; i < b.length - 1; i += 7) {
3627 var b8 = b.substr(i, 7);
3628 if (i != b.length - 7) b8 = '1' + b8;
3629 h += itox(parseInt(b8, 2));
3634 if (! oidString.match(/^[0-9.]+$/)) {
3635 throw "malformed oid string: " + oidString;
3638 var a = oidString.split('.');
3639 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
3642 for (var i = 0; i < a.length; i++) {
3649 // ********************************************************************
3650 // Abstract ASN.1 Classes
3651 // ********************************************************************
3653 // ********************************************************************
3656 * base class for ASN.1 DER encoder object
3657 * @name KJUR.asn1.ASN1Object
3658 * @class base class for ASN.1 DER encoder object
3659 * @property {Boolean} isModified flag whether internal data was changed
3660 * @property {String} hTLV hexadecimal string of ASN.1 TLV
3661 * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
3662 * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
3663 * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
3666 KJUR.asn1.ASN1Object = function() {
3670 * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
3671 * @name getLengthHexFromValue
3672 * @memberOf KJUR.asn1.ASN1Object#
3674 * @return {String} hexadecimal string of ASN.1 TLV length(L)
3676 this.getLengthHexFromValue = function() {
3677 if (typeof this.hV == "undefined" || this.hV == null) {
3678 throw "this.hV is null or undefined.";
3680 if (this.hV.length % 2 == 1) {
3681 throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
3683 var n = this.hV.length / 2;
3684 var hN = n.toString(16);
3685 if (hN.length % 2 == 1) {
3691 var hNlen = hN.length / 2;
3693 throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
3695 var head = 128 + hNlen;
3696 return head.toString(16) + hN;
3701 * get hexadecimal string of ASN.1 TLV bytes
3702 * @name getEncodedHex
3703 * @memberOf KJUR.asn1.ASN1Object#
3705 * @return {String} hexadecimal string of ASN.1 TLV
3707 this.getEncodedHex = function() {
3708 if (this.hTLV == null || this.isModified) {
3709 this.hV = this.getFreshValueHex();
3710 this.hL = this.getLengthHexFromValue();
3711 this.hTLV = this.hT + this.hL + this.hV;
3712 this.isModified = false;
3713 //alert("first time: " + this.hTLV);
3719 * get hexadecimal string of ASN.1 TLV value(V) bytes
3721 * @memberOf KJUR.asn1.ASN1Object#
3723 * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
3725 this.getValueHex = function() {
3726 this.getEncodedHex();
3730 this.getFreshValueHex = function() {
3735 // == BEGIN DERAbstractString ================================================
3737 * base class for ASN.1 DER string classes
3738 * @name KJUR.asn1.DERAbstractString
3739 * @class base class for ASN.1 DER string classes
3740 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
3741 * @property {String} s internal string of value
3742 * @extends KJUR.asn1.ASN1Object
3745 * As for argument 'params' for constructor, you can specify one of
3746 * following properties:
3748 * <li>str - specify initial ASN.1 value(V) by a string</li>
3749 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
3751 * NOTE: 'params' can be omitted.
3753 KJUR.asn1.DERAbstractString = function(params) {
3754 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3757 * get string value of this string object
3759 * @memberOf KJUR.asn1.DERAbstractString#
3761 * @return {String} string value of this string object
3763 this.getString = function() {
3768 * set value by a string
3770 * @memberOf KJUR.asn1.DERAbstractString#
3772 * @param {String} newS value by a string to set
3774 this.setString = function(newS) {
3776 this.isModified = true;
3778 this.hV = stohex(this.s);
3782 * set value by a hexadecimal string
3783 * @name setStringHex
3784 * @memberOf KJUR.asn1.DERAbstractString#
3786 * @param {String} newHexString value by a hexadecimal string to set
3788 this.setStringHex = function(newHexString) {
3790 this.isModified = true;
3792 this.hV = newHexString;
3795 this.getFreshValueHex = function() {
3799 if (typeof params != "undefined") {
3800 if (typeof params == "string") {
3801 this.setString(params);
3802 } else if (typeof params['str'] != "undefined") {
3803 this.setString(params['str']);
3804 } else if (typeof params['hex'] != "undefined") {
3805 this.setStringHex(params['hex']);
3809 YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
3810 // == END DERAbstractString ================================================
3812 // == BEGIN DERAbstractTime ==================================================
3814 * base class for ASN.1 DER Generalized/UTCTime class
3815 * @name KJUR.asn1.DERAbstractTime
3816 * @class base class for ASN.1 DER Generalized/UTCTime class
3817 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
3818 * @extends KJUR.asn1.ASN1Object
3820 * @see KJUR.asn1.ASN1Object - superclass
3822 KJUR.asn1.DERAbstractTime = function(params) {
3823 KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
3825 // --- PRIVATE METHODS --------------------
3826 this.localDateToUTC = function(d) {
3827 utc = d.getTime() + (d.getTimezoneOffset() * 60000);
3828 var utcDate = new Date(utc);
3833 * format date string by Data object
3835 * @memberOf KJUR.asn1.AbstractTime;
3836 * @param {Date} dateObject
3837 * @param {string} type 'utc' or 'gen'
3838 * @param {boolean} withMillis flag for with millisections or not
3840 * 'withMillis' flag is supported from asn1 1.0.6.
3842 this.formatDate = function(dateObject, type, withMillis) {
3843 var pad = this.zeroPadding;
3844 var d = this.localDateToUTC(dateObject);
3845 var year = String(d.getFullYear());
3846 if (type == 'utc') year = year.substr(2, 2);
3847 var month = pad(String(d.getMonth() + 1), 2);
3848 var day = pad(String(d.getDate()), 2);
3849 var hour = pad(String(d.getHours()), 2);
3850 var min = pad(String(d.getMinutes()), 2);
3851 var sec = pad(String(d.getSeconds()), 2);
3852 var s = year + month + day + hour + min + sec;
3853 if (withMillis === true) {
3854 var millis = d.getMilliseconds();
3856 var sMillis = pad(String(millis), 3);
3857 sMillis = sMillis.replace(/[0]+$/, "");
3858 s = s + "." + sMillis;
3864 this.zeroPadding = function(s, len) {
3865 if (s.length >= len) return s;
3866 return new Array(len - s.length + 1).join('0') + s;
3869 // --- PUBLIC METHODS --------------------
3871 * get string value of this string object
3873 * @memberOf KJUR.asn1.DERAbstractTime#
3875 * @return {String} string value of this time object
3877 this.getString = function() {
3882 * set value by a string
3884 * @memberOf KJUR.asn1.DERAbstractTime#
3886 * @param {String} newS value by a string to set such like "130430235959Z"
3888 this.setString = function(newS) {
3890 this.isModified = true;
3892 this.hV = stohex(newS);
3896 * set value by a Date object
3897 * @name setByDateValue
3898 * @memberOf KJUR.asn1.DERAbstractTime#
3900 * @param {Integer} year year of date (ex. 2013)
3901 * @param {Integer} month month of date between 1 and 12 (ex. 12)
3902 * @param {Integer} day day of month
3903 * @param {Integer} hour hours of date
3904 * @param {Integer} min minutes of date
3905 * @param {Integer} sec seconds of date
3907 this.setByDateValue = function(year, month, day, hour, min, sec) {
3908 var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
3909 this.setByDate(dateObject);
3912 this.getFreshValueHex = function() {
3916 YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
3917 // == END DERAbstractTime ==================================================
3919 // == BEGIN DERAbstractStructured ============================================
3921 * base class for ASN.1 DER structured class
3922 * @name KJUR.asn1.DERAbstractStructured
3923 * @class base class for ASN.1 DER structured class
3924 * @property {Array} asn1Array internal array of ASN1Object
3925 * @extends KJUR.asn1.ASN1Object
3927 * @see KJUR.asn1.ASN1Object - superclass
3929 KJUR.asn1.DERAbstractStructured = function(params) {
3930 KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
3933 * set value by array of ASN1Object
3934 * @name setByASN1ObjectArray
3935 * @memberOf KJUR.asn1.DERAbstractStructured#
3937 * @param {array} asn1ObjectArray array of ASN1Object to set
3939 this.setByASN1ObjectArray = function(asn1ObjectArray) {
3941 this.isModified = true;
3942 this.asn1Array = asn1ObjectArray;
3946 * append an ASN1Object to internal array
3947 * @name appendASN1Object
3948 * @memberOf KJUR.asn1.DERAbstractStructured#
3950 * @param {ASN1Object} asn1Object to add
3952 this.appendASN1Object = function(asn1Object) {
3954 this.isModified = true;
3955 this.asn1Array.push(asn1Object);
3958 this.asn1Array = new Array();
3959 if (typeof params != "undefined") {
3960 if (typeof params['array'] != "undefined") {
3961 this.asn1Array = params['array'];
3965 YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
3968 // ********************************************************************
3969 // ASN.1 Object Classes
3970 // ********************************************************************
3972 // ********************************************************************
3974 * class for ASN.1 DER Boolean
3975 * @name KJUR.asn1.DERBoolean
3976 * @class class for ASN.1 DER Boolean
3977 * @extends KJUR.asn1.ASN1Object
3979 * @see KJUR.asn1.ASN1Object - superclass
3981 KJUR.asn1.DERBoolean = function() {
3982 KJUR.asn1.DERBoolean.superclass.constructor.call(this);
3984 this.hTLV = "0101ff";
3986 YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
3988 // ********************************************************************
3990 * class for ASN.1 DER Integer
3991 * @name KJUR.asn1.DERInteger
3992 * @class class for ASN.1 DER Integer
3993 * @extends KJUR.asn1.ASN1Object
3996 * As for argument 'params' for constructor, you can specify one of
3997 * following properties:
3999 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4000 * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
4001 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4003 * NOTE: 'params' can be omitted.
4005 KJUR.asn1.DERInteger = function(params) {
4006 KJUR.asn1.DERInteger.superclass.constructor.call(this);
4010 * set value by Tom Wu's BigInteger object
4011 * @name setByBigInteger
4012 * @memberOf KJUR.asn1.DERInteger#
4014 * @param {BigInteger} bigIntegerValue to set
4016 this.setByBigInteger = function(bigIntegerValue) {
4018 this.isModified = true;
4019 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4023 * set value by integer value
4024 * @name setByInteger
4025 * @memberOf KJUR.asn1.DERInteger
4027 * @param {Integer} integer value to set
4029 this.setByInteger = function(intValue) {
4030 var bi = new BigInteger(String(intValue), 10);
4031 this.setByBigInteger(bi);
4035 * set value by integer value
4037 * @memberOf KJUR.asn1.DERInteger#
4039 * @param {String} hexadecimal string of integer value
4042 * NOTE: Value shall be represented by minimum octet length of
4043 * two's complement representation.
4045 * new KJUR.asn1.DERInteger(123);
4046 * new KJUR.asn1.DERInteger({'int': 123});
4047 * new KJUR.asn1.DERInteger({'hex': '1fad'});
4049 this.setValueHex = function(newHexString) {
4050 this.hV = newHexString;
4053 this.getFreshValueHex = function() {
4057 if (typeof params != "undefined") {
4058 if (typeof params['bigint'] != "undefined") {
4059 this.setByBigInteger(params['bigint']);
4060 } else if (typeof params['int'] != "undefined") {
4061 this.setByInteger(params['int']);
4062 } else if (typeof params == "number") {
4063 this.setByInteger(params);
4064 } else if (typeof params['hex'] != "undefined") {
4065 this.setValueHex(params['hex']);
4069 YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
4071 // ********************************************************************
4073 * class for ASN.1 DER encoded BitString primitive
4074 * @name KJUR.asn1.DERBitString
4075 * @class class for ASN.1 DER encoded BitString primitive
4076 * @extends KJUR.asn1.ASN1Object
4079 * As for argument 'params' for constructor, you can specify one of
4080 * following properties:
4082 * <li>bin - specify binary string (ex. '10111')</li>
4083 * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
4084 * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
4085 * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
4086 * argument for "BitString encapsulates" structure.</li>
4088 * NOTE1: 'params' can be omitted.<br/>
4089 * NOTE2: 'obj' parameter have been supported since
4090 * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
4092 * // default constructor
4093 * o = new KJUR.asn1.DERBitString();
4094 * // initialize with binary string
4095 * o = new KJUR.asn1.DERBitString({bin: "1011"});
4096 * // initialize with boolean array
4097 * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
4098 * // initialize with hexadecimal string (04 is unused bits)
4099 * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
4100 * // initialize with ASN1Util.newObject argument for encapsulated
4101 * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4102 * // above generates a ASN.1 data like this:
4103 * // BIT STRING, encapsulates {
4106 * // PrintableString 'aaa'
4110 KJUR.asn1.DERBitString = function(params) {
4111 if (params !== undefined && typeof params.obj !== "undefined") {
4112 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4113 params.hex = "00" + o.getEncodedHex();
4115 KJUR.asn1.DERBitString.superclass.constructor.call(this);
4119 * set ASN.1 value(V) by a hexadecimal string including unused bits
4120 * @name setHexValueIncludingUnusedBits
4121 * @memberOf KJUR.asn1.DERBitString#
4123 * @param {String} newHexStringIncludingUnusedBits
4125 this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
4127 this.isModified = true;
4128 this.hV = newHexStringIncludingUnusedBits;
4132 * set ASN.1 value(V) by unused bit and hexadecimal string of value
4133 * @name setUnusedBitsAndHexValue
4134 * @memberOf KJUR.asn1.DERBitString#
4136 * @param {Integer} unusedBits
4137 * @param {String} hValue
4139 this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
4140 if (unusedBits < 0 || 7 < unusedBits) {
4141 throw "unused bits shall be from 0 to 7: u = " + unusedBits;
4143 var hUnusedBits = "0" + unusedBits;
4145 this.isModified = true;
4146 this.hV = hUnusedBits + hValue;
4150 * set ASN.1 DER BitString by binary string<br/>
4151 * @name setByBinaryString
4152 * @memberOf KJUR.asn1.DERBitString#
4154 * @param {String} binaryString binary value string (i.e. '10111')
4156 * Its unused bits will be calculated automatically by length of
4157 * 'binaryValue'. <br/>
4158 * NOTE: Trailing zeros '0' will be ignored.
4160 * o = new KJUR.asn1.DERBitString();
4161 * o.setByBooleanArray("01011");
4163 this.setByBinaryString = function(binaryString) {
4164 binaryString = binaryString.replace(/0+$/, '');
4165 var unusedBits = 8 - binaryString.length % 8;
4166 if (unusedBits == 8) unusedBits = 0;
4167 for (var i = 0; i <= unusedBits; i++) {
4168 binaryString += '0';
4171 for (var i = 0; i < binaryString.length - 1; i += 8) {
4172 var b = binaryString.substr(i, 8);
4173 var x = parseInt(b, 2).toString(16);
4174 if (x.length == 1) x = '0' + x;
4178 this.isModified = true;
4179 this.hV = '0' + unusedBits + h;
4183 * set ASN.1 TLV value(V) by an array of boolean<br/>
4184 * @name setByBooleanArray
4185 * @memberOf KJUR.asn1.DERBitString#
4187 * @param {array} booleanArray array of boolean (ex. [true, false, true])
4189 * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
4191 * o = new KJUR.asn1.DERBitString();
4192 * o.setByBooleanArray([false, true, false, true, true]);
4194 this.setByBooleanArray = function(booleanArray) {
4196 for (var i = 0; i < booleanArray.length; i++) {
4197 if (booleanArray[i] == true) {
4203 this.setByBinaryString(s);
4207 * generate an array of falses with specified length<br/>
4208 * @name newFalseArray
4209 * @memberOf KJUR.asn1.DERBitString
4211 * @param {Integer} nLength length of array to generate
4212 * @return {array} array of boolean falses
4214 * This static method may be useful to initialize boolean array.
4216 * o = new KJUR.asn1.DERBitString();
4217 * o.newFalseArray(3) → [false, false, false]
4219 this.newFalseArray = function(nLength) {
4220 var a = new Array(nLength);
4221 for (var i = 0; i < nLength; i++) {
4227 this.getFreshValueHex = function() {
4231 if (typeof params != "undefined") {
4232 if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
4233 this.setHexValueIncludingUnusedBits(params);
4234 } else if (typeof params['hex'] != "undefined") {
4235 this.setHexValueIncludingUnusedBits(params['hex']);
4236 } else if (typeof params['bin'] != "undefined") {
4237 this.setByBinaryString(params['bin']);
4238 } else if (typeof params['array'] != "undefined") {
4239 this.setByBooleanArray(params['array']);
4243 YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
4245 // ********************************************************************
4247 * class for ASN.1 DER OctetString<br/>
4248 * @name KJUR.asn1.DEROctetString
4249 * @class class for ASN.1 DER OctetString
4250 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4251 * @extends KJUR.asn1.DERAbstractString
4253 * This class provides ASN.1 OctetString simple type.<br/>
4254 * Supported "params" attributes are:
4256 * <li>str - to set a string as a value</li>
4257 * <li>hex - to set a hexadecimal string as a value</li>
4258 * <li>obj - to set a encapsulated ASN.1 value by JSON object
4259 * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
4261 * NOTE: A parameter 'obj' have been supported
4262 * for "OCTET STRING, encapsulates" structure.
4263 * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
4264 * @see KJUR.asn1.DERAbstractString - superclass
4266 * // default constructor
4267 * o = new KJUR.asn1.DEROctetString();
4268 * // initialize with string
4269 * o = new KJUR.asn1.DEROctetString({str: "aaa"});
4270 * // initialize with hexadecimal string
4271 * o = new KJUR.asn1.DEROctetString({hex: "616161"});
4272 * // initialize with ASN1Util.newObject argument
4273 * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
4274 * // above generates a ASN.1 data like this:
4275 * // OCTET STRING, encapsulates {
4278 * // PrintableString 'aaa'
4282 KJUR.asn1.DEROctetString = function(params) {
4283 if (params !== undefined && typeof params.obj !== "undefined") {
4284 var o = KJUR.asn1.ASN1Util.newObject(params.obj);
4285 params.hex = o.getEncodedHex();
4287 KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
4290 YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
4292 // ********************************************************************
4294 * class for ASN.1 DER Null
4295 * @name KJUR.asn1.DERNull
4296 * @class class for ASN.1 DER Null
4297 * @extends KJUR.asn1.ASN1Object
4299 * @see KJUR.asn1.ASN1Object - superclass
4301 KJUR.asn1.DERNull = function() {
4302 KJUR.asn1.DERNull.superclass.constructor.call(this);
4306 YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
4308 // ********************************************************************
4310 * class for ASN.1 DER ObjectIdentifier
4311 * @name KJUR.asn1.DERObjectIdentifier
4312 * @class class for ASN.1 DER ObjectIdentifier
4313 * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
4314 * @extends KJUR.asn1.ASN1Object
4317 * As for argument 'params' for constructor, you can specify one of
4318 * following properties:
4320 * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
4321 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4323 * NOTE: 'params' can be omitted.
4325 KJUR.asn1.DERObjectIdentifier = function(params) {
4326 var itox = function(i) {
4327 var h = i.toString(16);
4328 if (h.length == 1) h = '0' + h;
4331 var roidtox = function(roid) {
4333 var bi = new BigInteger(roid, 10);
4334 var b = bi.toString(2);
4335 var padLen = 7 - b.length % 7;
4336 if (padLen == 7) padLen = 0;
4338 for (var i = 0; i < padLen; i++) bPad += '0';
4340 for (var i = 0; i < b.length - 1; i += 7) {
4341 var b8 = b.substr(i, 7);
4342 if (i != b.length - 7) b8 = '1' + b8;
4343 h += itox(parseInt(b8, 2));
4348 KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
4352 * set value by a hexadecimal string
4354 * @memberOf KJUR.asn1.DERObjectIdentifier#
4356 * @param {String} newHexString hexadecimal value of OID bytes
4358 this.setValueHex = function(newHexString) {
4360 this.isModified = true;
4362 this.hV = newHexString;
4366 * set value by a OID string<br/>
4367 * @name setValueOidString
4368 * @memberOf KJUR.asn1.DERObjectIdentifier#
4370 * @param {String} oidString OID string (ex. 2.5.4.13)
4372 * o = new KJUR.asn1.DERObjectIdentifier();
4373 * o.setValueOidString("2.5.4.13");
4375 this.setValueOidString = function(oidString) {
4376 if (! oidString.match(/^[0-9.]+$/)) {
4377 throw "malformed oid string: " + oidString;
4380 var a = oidString.split('.');
4381 var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
4384 for (var i = 0; i < a.length; i++) {
4388 this.isModified = true;
4394 * set value by a OID name
4395 * @name setValueName
4396 * @memberOf KJUR.asn1.DERObjectIdentifier#
4398 * @param {String} oidName OID name (ex. 'serverAuth')
4401 * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
4402 * Otherwise raise error.
4404 * o = new KJUR.asn1.DERObjectIdentifier();
4405 * o.setValueName("serverAuth");
4407 this.setValueName = function(oidName) {
4408 var oid = KJUR.asn1.x509.OID.name2oid(oidName);
4410 this.setValueOidString(oid);
4412 throw "DERObjectIdentifier oidName undefined: " + oidName;
4416 this.getFreshValueHex = function() {
4420 if (params !== undefined) {
4421 if (typeof params === "string") {
4422 if (params.match(/^[0-2].[0-9.]+$/)) {
4423 this.setValueOidString(params);
4425 this.setValueName(params);
4427 } else if (params.oid !== undefined) {
4428 this.setValueOidString(params.oid);
4429 } else if (params.hex !== undefined) {
4430 this.setValueHex(params.hex);
4431 } else if (params.name !== undefined) {
4432 this.setValueName(params.name);
4436 YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
4438 // ********************************************************************
4440 * class for ASN.1 DER Enumerated
4441 * @name KJUR.asn1.DEREnumerated
4442 * @class class for ASN.1 DER Enumerated
4443 * @extends KJUR.asn1.ASN1Object
4446 * As for argument 'params' for constructor, you can specify one of
4447 * following properties:
4449 * <li>int - specify initial ASN.1 value(V) by integer value</li>
4450 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4452 * NOTE: 'params' can be omitted.
4454 * new KJUR.asn1.DEREnumerated(123);
4455 * new KJUR.asn1.DEREnumerated({int: 123});
4456 * new KJUR.asn1.DEREnumerated({hex: '1fad'});
4458 KJUR.asn1.DEREnumerated = function(params) {
4459 KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
4463 * set value by Tom Wu's BigInteger object
4464 * @name setByBigInteger
4465 * @memberOf KJUR.asn1.DEREnumerated#
4467 * @param {BigInteger} bigIntegerValue to set
4469 this.setByBigInteger = function(bigIntegerValue) {
4471 this.isModified = true;
4472 this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
4476 * set value by integer value
4477 * @name setByInteger
4478 * @memberOf KJUR.asn1.DEREnumerated#
4480 * @param {Integer} integer value to set
4482 this.setByInteger = function(intValue) {
4483 var bi = new BigInteger(String(intValue), 10);
4484 this.setByBigInteger(bi);
4488 * set value by integer value
4490 * @memberOf KJUR.asn1.DEREnumerated#
4492 * @param {String} hexadecimal string of integer value
4495 * NOTE: Value shall be represented by minimum octet length of
4496 * two's complement representation.
4498 this.setValueHex = function(newHexString) {
4499 this.hV = newHexString;
4502 this.getFreshValueHex = function() {
4506 if (typeof params != "undefined") {
4507 if (typeof params['int'] != "undefined") {
4508 this.setByInteger(params['int']);
4509 } else if (typeof params == "number") {
4510 this.setByInteger(params);
4511 } else if (typeof params['hex'] != "undefined") {
4512 this.setValueHex(params['hex']);
4516 YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
4518 // ********************************************************************
4520 * class for ASN.1 DER UTF8String
4521 * @name KJUR.asn1.DERUTF8String
4522 * @class class for ASN.1 DER UTF8String
4523 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4524 * @extends KJUR.asn1.DERAbstractString
4526 * @see KJUR.asn1.DERAbstractString - superclass
4528 KJUR.asn1.DERUTF8String = function(params) {
4529 KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
4532 YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
4534 // ********************************************************************
4536 * class for ASN.1 DER NumericString
4537 * @name KJUR.asn1.DERNumericString
4538 * @class class for ASN.1 DER NumericString
4539 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4540 * @extends KJUR.asn1.DERAbstractString
4542 * @see KJUR.asn1.DERAbstractString - superclass
4544 KJUR.asn1.DERNumericString = function(params) {
4545 KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
4548 YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
4550 // ********************************************************************
4552 * class for ASN.1 DER PrintableString
4553 * @name KJUR.asn1.DERPrintableString
4554 * @class class for ASN.1 DER PrintableString
4555 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4556 * @extends KJUR.asn1.DERAbstractString
4558 * @see KJUR.asn1.DERAbstractString - superclass
4560 KJUR.asn1.DERPrintableString = function(params) {
4561 KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
4564 YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
4566 // ********************************************************************
4568 * class for ASN.1 DER TeletexString
4569 * @name KJUR.asn1.DERTeletexString
4570 * @class class for ASN.1 DER TeletexString
4571 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4572 * @extends KJUR.asn1.DERAbstractString
4574 * @see KJUR.asn1.DERAbstractString - superclass
4576 KJUR.asn1.DERTeletexString = function(params) {
4577 KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
4580 YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
4582 // ********************************************************************
4584 * class for ASN.1 DER IA5String
4585 * @name KJUR.asn1.DERIA5String
4586 * @class class for ASN.1 DER IA5String
4587 * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
4588 * @extends KJUR.asn1.DERAbstractString
4590 * @see KJUR.asn1.DERAbstractString - superclass
4592 KJUR.asn1.DERIA5String = function(params) {
4593 KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
4596 YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
4598 // ********************************************************************
4600 * class for ASN.1 DER UTCTime
4601 * @name KJUR.asn1.DERUTCTime
4602 * @class class for ASN.1 DER UTCTime
4603 * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
4604 * @extends KJUR.asn1.DERAbstractTime
4607 * As for argument 'params' for constructor, you can specify one of
4608 * following properties:
4610 * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
4611 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4612 * <li>date - specify Date object.</li>
4614 * NOTE: 'params' can be omitted.
4617 * d1 = new KJUR.asn1.DERUTCTime();
4618 * d1.setString('130430125959Z');
4620 * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
4621 * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
4622 * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
4624 KJUR.asn1.DERUTCTime = function(params) {
4625 KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
4629 * set value by a Date object<br/>
4631 * @memberOf KJUR.asn1.DERUTCTime#
4633 * @param {Date} dateObject Date object to set ASN.1 value(V)
4635 * o = new KJUR.asn1.DERUTCTime();
4636 * o.setByDate(new Date("2016/12/31"));
4638 this.setByDate = function(dateObject) {
4640 this.isModified = true;
4641 this.date = dateObject;
4642 this.s = this.formatDate(this.date, 'utc');
4643 this.hV = stohex(this.s);
4646 this.getFreshValueHex = function() {
4647 if (typeof this.date == "undefined" && typeof this.s == "undefined") {
4648 this.date = new Date();
4649 this.s = this.formatDate(this.date, 'utc');
4650 this.hV = stohex(this.s);
4655 if (params !== undefined) {
4656 if (params.str !== undefined) {
4657 this.setString(params.str);
4658 } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
4659 this.setString(params);
4660 } else if (params.hex !== undefined) {
4661 this.setStringHex(params.hex);
4662 } else if (params.date !== undefined) {
4663 this.setByDate(params.date);
4667 YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
4669 // ********************************************************************
4671 * class for ASN.1 DER GeneralizedTime
4672 * @name KJUR.asn1.DERGeneralizedTime
4673 * @class class for ASN.1 DER GeneralizedTime
4674 * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
4675 * @property {Boolean} withMillis flag to show milliseconds or not
4676 * @extends KJUR.asn1.DERAbstractTime
4679 * As for argument 'params' for constructor, you can specify one of
4680 * following properties:
4682 * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
4683 * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
4684 * <li>date - specify Date object.</li>
4685 * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
4687 * NOTE1: 'params' can be omitted.
4688 * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
4690 KJUR.asn1.DERGeneralizedTime = function(params) {
4691 KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
4693 this.withMillis = false;
4696 * set value by a Date object
4698 * @memberOf KJUR.asn1.DERGeneralizedTime#
4700 * @param {Date} dateObject Date object to set ASN.1 value(V)
4702 * When you specify UTC time, use 'Date.UTC' method like this:<br/>
4703 * o1 = new DERUTCTime();
4704 * o1.setByDate(date);
4706 * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
4708 this.setByDate = function(dateObject) {
4710 this.isModified = true;
4711 this.date = dateObject;
4712 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4713 this.hV = stohex(this.s);
4716 this.getFreshValueHex = function() {
4717 if (this.date === undefined && this.s === undefined) {
4718 this.date = new Date();
4719 this.s = this.formatDate(this.date, 'gen', this.withMillis);
4720 this.hV = stohex(this.s);
4725 if (params !== undefined) {
4726 if (params.str !== undefined) {
4727 this.setString(params.str);
4728 } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
4729 this.setString(params);
4730 } else if (params.hex !== undefined) {
4731 this.setStringHex(params.hex);
4732 } else if (params.date !== undefined) {
4733 this.setByDate(params.date);
4735 if (params.millis === true) {
4736 this.withMillis = true;
4740 YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
4742 // ********************************************************************
4744 * class for ASN.1 DER Sequence
4745 * @name KJUR.asn1.DERSequence
4746 * @class class for ASN.1 DER Sequence
4747 * @extends KJUR.asn1.DERAbstractStructured
4750 * As for argument 'params' for constructor, you can specify one of
4751 * following properties:
4753 * <li>array - specify array of ASN1Object to set elements of content</li>
4755 * NOTE: 'params' can be omitted.
4757 KJUR.asn1.DERSequence = function(params) {
4758 KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
4760 this.getFreshValueHex = function() {
4762 for (var i = 0; i < this.asn1Array.length; i++) {
4763 var asn1Obj = this.asn1Array[i];
4764 h += asn1Obj.getEncodedHex();
4770 YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
4772 // ********************************************************************
4774 * class for ASN.1 DER Set
4775 * @name KJUR.asn1.DERSet
4776 * @class class for ASN.1 DER Set
4777 * @extends KJUR.asn1.DERAbstractStructured
4780 * As for argument 'params' for constructor, you can specify one of
4781 * following properties:
4783 * <li>array - specify array of ASN1Object to set elements of content</li>
4784 * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
4786 * NOTE1: 'params' can be omitted.<br/>
4787 * NOTE2: sortflag is supported since 1.0.5.
4789 KJUR.asn1.DERSet = function(params) {
4790 KJUR.asn1.DERSet.superclass.constructor.call(this, params);
4792 this.sortFlag = true; // item shall be sorted only in ASN.1 DER
4793 this.getFreshValueHex = function() {
4794 var a = new Array();
4795 for (var i = 0; i < this.asn1Array.length; i++) {
4796 var asn1Obj = this.asn1Array[i];
4797 a.push(asn1Obj.getEncodedHex());
4799 if (this.sortFlag == true) a.sort();
4800 this.hV = a.join('');
4804 if (typeof params != "undefined") {
4805 if (typeof params.sortflag != "undefined" &&
4806 params.sortflag == false)
4807 this.sortFlag = false;
4810 YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
4812 // ********************************************************************
4814 * class for ASN.1 DER TaggedObject
4815 * @name KJUR.asn1.DERTaggedObject
4816 * @class class for ASN.1 DER TaggedObject
4817 * @extends KJUR.asn1.ASN1Object
4820 * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
4821 * For example, if you find '[1]' tag in a ASN.1 dump,
4822 * 'tagNoHex' will be 'a1'.
4824 * As for optional argument 'params' for constructor, you can specify *ANY* of
4825 * following properties:
4827 * <li>explicit - specify true if this is explicit tag otherwise false
4828 * (default is 'true').</li>
4829 * <li>tag - specify tag (default is 'a0' which means [0])</li>
4830 * <li>obj - specify ASN1Object which is tagged</li>
4833 * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
4834 * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
4835 * hex = d2.getEncodedHex();
4837 KJUR.asn1.DERTaggedObject = function(params) {
4838 KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
4841 this.isExplicit = true;
4842 this.asn1Object = null;
4845 * set value by an ASN1Object
4847 * @memberOf KJUR.asn1.DERTaggedObject#
4849 * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
4850 * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
4851 * @param {ASN1Object} asn1Object ASN.1 to encapsulate
4853 this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
4855 this.isExplicit = isExplicitFlag;
4856 this.asn1Object = asn1Object;
4857 if (this.isExplicit) {
4858 this.hV = this.asn1Object.getEncodedHex();
4860 this.isModified = true;
4863 this.hTLV = asn1Object.getEncodedHex();
4864 this.hTLV = this.hTLV.replace(/^../, tagNoHex);
4865 this.isModified = false;
4869 this.getFreshValueHex = function() {
4873 if (typeof params != "undefined") {
4874 if (typeof params['tag'] != "undefined") {
4875 this.hT = params['tag'];
4877 if (typeof params['explicit'] != "undefined") {
4878 this.isExplicit = params['explicit'];
4880 if (typeof params['obj'] != "undefined") {
4881 this.asn1Object = params['obj'];
4882 this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
4886 YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
4889 * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
4890 * This object is just a decorator for parsing the key parameter
4891 * @param {string|Object} key - The key in string format, or an object containing
4892 * the parameters needed to build a RSAKey object.
4895 var JSEncryptRSAKey = /** @class */ (function (_super) {
4896 __extends(JSEncryptRSAKey, _super);
4897 function JSEncryptRSAKey(key) {
4898 var _this = _super.call(this) || this;
4899 // Call the super constructor.
4900 // RSAKey.call(this);
4901 // If a key key was provided.
4903 // If this is a string...
4904 if (typeof key === "string") {
4905 _this.parseKey(key);
4907 else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
4908 JSEncryptRSAKey.hasPublicKeyProperty(key)) {
4909 // Set the values for the key.
4910 _this.parsePropertiesFrom(key);
4916 * Method to parse a pem encoded string containing both a public or private key.
4917 * The method will translate the pem encoded string in a der encoded string and
4918 * will parse private key and public key parameters. This method accepts public key
4919 * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
4921 * @todo Check how many rsa formats use the same format of pkcs #1.
4923 * The format is defined as:
4924 * PublicKeyInfo ::= SEQUENCE {
4925 * algorithm AlgorithmIdentifier,
4926 * PublicKey BIT STRING
4928 * Where AlgorithmIdentifier is:
4929 * AlgorithmIdentifier ::= SEQUENCE {
4930 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
4931 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
4933 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
4934 * RSAPublicKey ::= SEQUENCE {
4935 * modulus INTEGER, -- n
4936 * publicExponent INTEGER -- e
4938 * it's possible to examine the structure of the keys obtained from openssl using
4939 * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
4940 * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
4943 JSEncryptRSAKey.prototype.parseKey = function (pem) {
4946 var public_exponent = 0;
4947 var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
4948 var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
4949 var asn1 = ASN1.decode(der);
4950 // Fixes a bug with OpenSSL 1.0+ private keys
4951 if (asn1.sub.length === 3) {
4952 asn1 = asn1.sub[2].sub[0];
4954 if (asn1.sub.length === 9) {
4955 // Parse the private key.
4956 modulus = asn1.sub[1].getHexStringValue(); // bigint
4957 this.n = parseBigInt(modulus, 16);
4958 public_exponent = asn1.sub[2].getHexStringValue(); // int
4959 this.e = parseInt(public_exponent, 16);
4960 var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
4961 this.d = parseBigInt(private_exponent, 16);
4962 var prime1 = asn1.sub[4].getHexStringValue(); // bigint
4963 this.p = parseBigInt(prime1, 16);
4964 var prime2 = asn1.sub[5].getHexStringValue(); // bigint
4965 this.q = parseBigInt(prime2, 16);
4966 var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
4967 this.dmp1 = parseBigInt(exponent1, 16);
4968 var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
4969 this.dmq1 = parseBigInt(exponent2, 16);
4970 var coefficient = asn1.sub[8].getHexStringValue(); // bigint
4971 this.coeff = parseBigInt(coefficient, 16);
4973 else if (asn1.sub.length === 2) {
4974 // Parse the public key.
4975 var bit_string = asn1.sub[1];
4976 var sequence = bit_string.sub[0];
4977 modulus = sequence.sub[0].getHexStringValue();
4978 this.n = parseBigInt(modulus, 16);
4979 public_exponent = sequence.sub[1].getHexStringValue();
4980 this.e = parseInt(public_exponent, 16);
4992 * Translate rsa parameters in a hex encoded string representing the rsa key.
4994 * The translation follow the ASN.1 notation :
4995 * RSAPrivateKey ::= SEQUENCE {
4997 * modulus INTEGER, -- n
4998 * publicExponent INTEGER, -- e
4999 * privateExponent INTEGER, -- d
5000 * prime1 INTEGER, -- p
5001 * prime2 INTEGER, -- q
5002 * exponent1 INTEGER, -- d mod (p1)
5003 * exponent2 INTEGER, -- d mod (q-1)
5004 * coefficient INTEGER, -- (inverse of q) mod p
5006 * @returns {string} DER Encoded String representing the rsa private key
5009 JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
5012 new KJUR.asn1.DERInteger({ int: 0 }),
5013 new KJUR.asn1.DERInteger({ bigint: this.n }),
5014 new KJUR.asn1.DERInteger({ int: this.e }),
5015 new KJUR.asn1.DERInteger({ bigint: this.d }),
5016 new KJUR.asn1.DERInteger({ bigint: this.p }),
5017 new KJUR.asn1.DERInteger({ bigint: this.q }),
5018 new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
5019 new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
5020 new KJUR.asn1.DERInteger({ bigint: this.coeff })
5023 var seq = new KJUR.asn1.DERSequence(options);
5024 return seq.getEncodedHex();
5027 * base64 (pem) encoded version of the DER encoded representation
5028 * @returns {string} pem encoded representation without header and footer
5031 JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
5032 return hex2b64(this.getPrivateBaseKey());
5035 * Translate rsa parameters in a hex encoded string representing the rsa public key.
5036 * The representation follow the ASN.1 notation :
5037 * PublicKeyInfo ::= SEQUENCE {
5038 * algorithm AlgorithmIdentifier,
5039 * PublicKey BIT STRING
5041 * Where AlgorithmIdentifier is:
5042 * AlgorithmIdentifier ::= SEQUENCE {
5043 * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
5044 * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
5046 * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
5047 * RSAPublicKey ::= SEQUENCE {
5048 * modulus INTEGER, -- n
5049 * publicExponent INTEGER -- e
5051 * @returns {string} DER Encoded String representing the rsa public key
5054 JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
5055 var first_sequence = new KJUR.asn1.DERSequence({
5057 new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
5058 new KJUR.asn1.DERNull()
5061 var second_sequence = new KJUR.asn1.DERSequence({
5063 new KJUR.asn1.DERInteger({ bigint: this.n }),
5064 new KJUR.asn1.DERInteger({ int: this.e })
5067 var bit_string = new KJUR.asn1.DERBitString({
5068 hex: "00" + second_sequence.getEncodedHex()
5070 var seq = new KJUR.asn1.DERSequence({
5076 return seq.getEncodedHex();
5079 * base64 (pem) encoded version of the DER encoded representation
5080 * @returns {string} pem encoded representation without header and footer
5083 JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
5084 return hex2b64(this.getPublicBaseKey());
5087 * wrap the string in block of width chars. The default value for rsa keys is 64
5089 * @param {string} str the pem encoded string without header and footer
5090 * @param {Number} [width=64] - the length the string has to be wrapped at
5094 JSEncryptRSAKey.wordwrap = function (str, width) {
5095 width = width || 64;
5099 var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
5100 return str.match(RegExp(regex, "g")).join("\n");
5103 * Retrieve the pem encoded private key
5104 * @returns {string} the pem encoded private key with header/footer
5107 JSEncryptRSAKey.prototype.getPrivateKey = function () {
5108 var key = "-----BEGIN RSA PRIVATE KEY-----\n";
5109 key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
5110 key += "-----END RSA PRIVATE KEY-----";
5114 * Retrieve the pem encoded public key
5115 * @returns {string} the pem encoded public key with header/footer
5118 JSEncryptRSAKey.prototype.getPublicKey = function () {
5119 var key = "-----BEGIN PUBLIC KEY-----\n";
5120 key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
5121 key += "-----END PUBLIC KEY-----";
5125 * Check if the object contains the necessary parameters to populate the rsa modulus
5126 * and public exponent parameters.
5127 * @param {Object} [obj={}] - An object that may contain the two public key
5129 * @returns {boolean} true if the object contains both the modulus and the public exponent
5130 * properties (n and e)
5131 * @todo check for types of n and e. N should be a parseable bigInt object, E should
5132 * be a parseable integer number
5135 JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
5137 return (obj.hasOwnProperty("n") &&
5138 obj.hasOwnProperty("e"));
5141 * Check if the object contains ALL the parameters of an RSA key.
5142 * @param {Object} [obj={}] - An object that may contain nine rsa key
5144 * @returns {boolean} true if the object contains all the parameters needed
5145 * @todo check for types of the parameters all the parameters but the public exponent
5146 * should be parseable bigint objects, the public exponent should be a parseable integer number
5149 JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
5151 return (obj.hasOwnProperty("n") &&
5152 obj.hasOwnProperty("e") &&
5153 obj.hasOwnProperty("d") &&
5154 obj.hasOwnProperty("p") &&
5155 obj.hasOwnProperty("q") &&
5156 obj.hasOwnProperty("dmp1") &&
5157 obj.hasOwnProperty("dmq1") &&
5158 obj.hasOwnProperty("coeff"));
5161 * Parse the properties of obj in the current rsa object. Obj should AT LEAST
5162 * include the modulus and public exponent (n, e) parameters.
5163 * @param {Object} obj - the object containing rsa parameters
5166 JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
5169 if (obj.hasOwnProperty("d")) {
5173 this.dmp1 = obj.dmp1;
5174 this.dmq1 = obj.dmq1;
5175 this.coeff = obj.coeff;
5178 return JSEncryptRSAKey;
5183 * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
5184 * possible parameters are:
5185 * - default_key_size {number} default: 1024 the key size in bit
5186 * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
5187 * - log {boolean} default: false whether log warn/error or not
5190 var JSEncrypt = /** @class */ (function () {
5191 function JSEncrypt(options) {
5192 options = options || {};
5193 this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
5194 this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
5195 this.log = options.log || false;
5196 // The private and public key.
5200 * Method to set the rsa key parameter (one method is enough to set both the public
5201 * and the private key, since the private key contains the public key paramenters)
5202 * Log a warning if logs are enabled
5203 * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
5206 JSEncrypt.prototype.setKey = function (key) {
5207 if (this.log && this.key) {
5208 console.warn("A key was already set, overriding existing.");
5210 this.key = new JSEncryptRSAKey(key);
5213 * Proxy method for setKey, for api compatibility
5217 JSEncrypt.prototype.setPrivateKey = function (privkey) {
5219 this.setKey(privkey);
5222 * Proxy method for setKey, for api compatibility
5226 JSEncrypt.prototype.setPublicKey = function (pubkey) {
5227 // Sets the public key.
5228 this.setKey(pubkey);
5231 * Proxy method for RSAKey object's decrypt, decrypt the string using the private
5232 * components of the rsa key object. Note that if the object was not set will be created
5233 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5234 * @param {string} str base64 encoded crypted string to decrypt
5235 * @return {string} the decrypted string
5238 JSEncrypt.prototype.decrypt = function (str) {
5239 // Return the decrypted string.
5241 return this.getKey().decrypt(b64tohex(str));
5248 * Proxy method for RSAKey object's encrypt, encrypt the string using the public
5249 * components of the rsa key object. Note that if the object was not set will be created
5250 * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
5251 * @param {string} str the string to encrypt
5252 * @return {string} the encrypted string encoded in base64
5255 JSEncrypt.prototype.encrypt = function (str) {
5256 // Return the encrypted string.
5258 return hex2b64(this.getKey().encrypt(str));
5265 * Proxy method for RSAKey object's sign.
5266 * @param {string} str the string to sign
5267 * @param {function} digestMethod hash method
5268 * @param {string} digestName the name of the hash algorithm
5269 * @return {string} the signature encoded in base64
5272 JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
5273 // return the RSA signature of 'str' in 'hex' format.
5275 return hex2b64(this.getKey().sign(str, digestMethod, digestName));
5282 * Proxy method for RSAKey object's verify.
5283 * @param {string} str the string to verify
5284 * @param {string} signature the signature encoded in base64 to compare the string to
5285 * @param {function} digestMethod hash method
5286 * @return {boolean} whether the data and signature match
5289 JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
5290 // Return the decrypted 'digest' of the signature.
5292 return this.getKey().verify(str, b64tohex(signature), digestMethod);
5299 * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
5300 * will be created and returned
5301 * @param {callback} [cb] the callback to be called if we want the key to be generated
5302 * in an async fashion
5303 * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
5306 JSEncrypt.prototype.getKey = function (cb) {
5307 // Only create new if it does not exist.
5309 // Get a new private key.
5310 this.key = new JSEncryptRSAKey();
5311 if (cb && {}.toString.call(cb) === "[object Function]") {
5312 this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
5315 // Generate the key.
5316 this.key.generate(this.default_key_size, this.default_public_exponent);
5321 * Returns the pem encoded representation of the private key
5322 * If the key doesn't exists a new key will be created
5323 * @returns {string} pem encoded representation of the private key WITH header and footer
5326 JSEncrypt.prototype.getPrivateKey = function () {
5327 // Return the private representation of this key.
5328 return this.getKey().getPrivateKey();
5331 * Returns the pem encoded representation of the private key
5332 * If the key doesn't exists a new key will be created
5333 * @returns {string} pem encoded representation of the private key WITHOUT header and footer
5336 JSEncrypt.prototype.getPrivateKeyB64 = function () {
5337 // Return the private representation of this key.
5338 return this.getKey().getPrivateBaseKeyB64();
5341 * Returns the pem encoded representation of the public key
5342 * If the key doesn't exists a new key will be created
5343 * @returns {string} pem encoded representation of the public key WITH header and footer
5346 JSEncrypt.prototype.getPublicKey = function () {
5347 // Return the private representation of this key.
5348 return this.getKey().getPublicKey();
5351 * Returns the pem encoded representation of the public key
5352 * If the key doesn't exists a new key will be created
5353 * @returns {string} pem encoded representation of the public key WITHOUT header and footer
5356 JSEncrypt.prototype.getPublicKeyB64 = function () {
5357 // Return the private representation of this key.
5358 return this.getKey().getPublicBaseKeyB64();
5360 JSEncrypt.version = "3.0.0-rc.1";
5364 window.JSEncrypt = JSEncrypt;
5366 exports.JSEncrypt = JSEncrypt;
5367 exports.default = JSEncrypt;
5369 Object.defineProperty(exports, '__esModule', { value: true });