• 几种常见的加密方式


    线性散列加密算法

    常见算法:MD5、SHA-1、SHA-256、HMAC

    主要特点:不可逆,一旦加密就不能反向解密得到密码原文。

    适用场景:用于存储用户私有信息,如交易密码等不可解密的信息。

    非对称加密算法

    常见算法:RSA、DSA、ECC

    主要特点:加密和解密采用不同的密钥(公钥和私钥)。

    优点:公钥加密,私钥解密;相比于对称加密,安全性更高。

    缺点:加密和解密花费时间长、速度慢,只适合对少量数据进行加密。

    适用场景:常用于传递用户敏感信息,但是需要进行解密验证的信息。

    对称加密算法

    常见算法:AES、DES、3DES

    主要特点:加密和解密采用相同的密钥(公用一个密钥)

    优点:加解密过程中计算量小、加密速度快、加密效率高。

    缺点:密钥的传递和保存是个问题,容易泄露,没有非对称加密安全。

    适用场景:一般用于保存用户手机号、身份证等敏感但能解密的信息。

    RSA加密使用

    1. import {
    2. rsaEncrypt
    3. } from '@/utils/rsa/rsa.js';
    4. password: rsaEncrypt(val);
    1. import { JSEncrypt } from './jsencrypt'
    2. // 加密公钥
    3. const publicKey = ``
    4. // 加密
    5. export function rsaEncrypt (msg) {
    6. const jsencrypt = new JSEncrypt()
    7. jsencrypt.setPublicKey(publicKey)
    8. const encryptMsg = jsencrypt.encrypt(msg)
    9. return encryptMsg
    10. }
    11. // 解密私钥
    12. const privateKey = ``
    13. // 解密
    14. export function rsaDecrypt (msg) {
    15. const decrypt = new JSEncrypt()
    16. decrypt.setPrivateKey(privateKey)
    17. const decryptMsg = decrypt.decrypt(msg)
    18. return decryptMsg
    19. }
    1. (function (global, factory) {
    2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
    4. (factory((global.JSEncrypt = {})));
    5. }(this, (function (exports) { 'use strict';
    6. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
    7. function int2char(n) {
    8. return BI_RM.charAt(n);
    9. }
    10. //#region BIT_OPERATIONS
    11. // (public) this & a
    12. function op_and(x, y) {
    13. return x & y;
    14. }
    15. // (public) this | a
    16. function op_or(x, y) {
    17. return x | y;
    18. }
    19. // (public) this ^ a
    20. function op_xor(x, y) {
    21. return x ^ y;
    22. }
    23. // (public) this & ~a
    24. function op_andnot(x, y) {
    25. return x & ~y;
    26. }
    27. // return index of lowest 1-bit in x, x < 2^31
    28. function lbit(x) {
    29. if (x == 0) {
    30. return -1;
    31. }
    32. var r = 0;
    33. if ((x & 0xffff) == 0) {
    34. x >>= 16;
    35. r += 16;
    36. }
    37. if ((x & 0xff) == 0) {
    38. x >>= 8;
    39. r += 8;
    40. }
    41. if ((x & 0xf) == 0) {
    42. x >>= 4;
    43. r += 4;
    44. }
    45. if ((x & 3) == 0) {
    46. x >>= 2;
    47. r += 2;
    48. }
    49. if ((x & 1) == 0) {
    50. ++r;
    51. }
    52. return r;
    53. }
    54. // return number of 1 bits in x
    55. function cbit(x) {
    56. var r = 0;
    57. while (x != 0) {
    58. x &= x - 1;
    59. ++r;
    60. }
    61. return r;
    62. }
    63. //#endregion BIT_OPERATIONS
    64. var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    65. var b64pad = "=";
    66. function hex2b64(h) {
    67. var i;
    68. var c;
    69. var ret = "";
    70. for (i = 0; i + 3 <= h.length; i += 3) {
    71. c = parseInt(h.substring(i, i + 3), 16);
    72. ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
    73. }
    74. if (i + 1 == h.length) {
    75. c = parseInt(h.substring(i, i + 1), 16);
    76. ret += b64map.charAt(c << 2);
    77. }
    78. else if (i + 2 == h.length) {
    79. c = parseInt(h.substring(i, i + 2), 16);
    80. ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
    81. }
    82. while ((ret.length & 3) > 0) {
    83. ret += b64pad;
    84. }
    85. return ret;
    86. }
    87. // convert a base64 string to hex
    88. function b64tohex(s) {
    89. var ret = "";
    90. var i;
    91. var k = 0; // b64 state, 0-3
    92. var slop = 0;
    93. for (i = 0; i < s.length; ++i) {
    94. if (s.charAt(i) == b64pad) {
    95. break;
    96. }
    97. var v = b64map.indexOf(s.charAt(i));
    98. if (v < 0) {
    99. continue;
    100. }
    101. if (k == 0) {
    102. ret += int2char(v >> 2);
    103. slop = v & 3;
    104. k = 1;
    105. }
    106. else if (k == 1) {
    107. ret += int2char((slop << 2) | (v >> 4));
    108. slop = v & 0xf;
    109. k = 2;
    110. }
    111. else if (k == 2) {
    112. ret += int2char(slop);
    113. ret += int2char(v >> 2);
    114. slop = v & 3;
    115. k = 3;
    116. }
    117. else {
    118. ret += int2char((slop << 2) | (v >> 4));
    119. ret += int2char(v & 0xf);
    120. k = 0;
    121. }
    122. }
    123. if (k == 1) {
    124. ret += int2char(slop << 2);
    125. }
    126. return ret;
    127. }
    128. /*! *****************************************************************************
    129. Copyright (c) Microsoft Corporation. All rights reserved.
    130. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    131. this file except in compliance with the License. You may obtain a copy of the
    132. License at http://www.apache.org/licenses/LICENSE-2.0
    133. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    134. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    135. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    136. MERCHANTABLITY OR NON-INFRINGEMENT.
    137. See the Apache Version 2.0 License for specific language governing permissions
    138. and limitations under the License.
    139. ***************************************************************************** */
    140. /* global Reflect, Promise */
    141. var extendStatics = function(d, b) {
    142. extendStatics = Object.setPrototypeOf ||
    143. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
    144. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    145. return extendStatics(d, b);
    146. };
    147. function __extends(d, b) {
    148. extendStatics(d, b);
    149. function __() { this.constructor = d; }
    150. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    151. }
    152. // Hex JavaScript decoder
    153. // Copyright (c) 2008-2013 Lapo Luchini
    154. // Permission to use, copy, modify, and/or distribute this software for any
    155. // purpose with or without fee is hereby granted, provided that the above
    156. // copyright notice and this permission notice appear in all copies.
    157. //
    158. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    159. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    160. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    161. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    162. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    163. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    164. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    165. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
    166. var decoder;
    167. var Hex = {
    168. decode: function (a) {
    169. var i;
    170. if (decoder === undefined) {
    171. var hex = "0123456789ABCDEF";
    172. var ignore = " \f\n\r\t\u00A0\u2028\u2029";
    173. decoder = {};
    174. for (i = 0; i < 16; ++i) {
    175. decoder[hex.charAt(i)] = i;
    176. }
    177. hex = hex.toLowerCase();
    178. for (i = 10; i < 16; ++i) {
    179. decoder[hex.charAt(i)] = i;
    180. }
    181. for (i = 0; i < ignore.length; ++i) {
    182. decoder[ignore.charAt(i)] = -1;
    183. }
    184. }
    185. var out = [];
    186. var bits = 0;
    187. var char_count = 0;
    188. for (i = 0; i < a.length; ++i) {
    189. var c = a.charAt(i);
    190. if (c == "=") {
    191. break;
    192. }
    193. c = decoder[c];
    194. if (c == -1) {
    195. continue;
    196. }
    197. if (c === undefined) {
    198. throw new Error("Illegal character at offset " + i);
    199. }
    200. bits |= c;
    201. if (++char_count >= 2) {
    202. out[out.length] = bits;
    203. bits = 0;
    204. char_count = 0;
    205. }
    206. else {
    207. bits <<= 4;
    208. }
    209. }
    210. if (char_count) {
    211. throw new Error("Hex encoding incomplete: 4 bits missing");
    212. }
    213. return out;
    214. }
    215. };
    216. // Base64 JavaScript decoder
    217. // Copyright (c) 2008-2013 Lapo Luchini
    218. // Permission to use, copy, modify, and/or distribute this software for any
    219. // purpose with or without fee is hereby granted, provided that the above
    220. // copyright notice and this permission notice appear in all copies.
    221. //
    222. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    223. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    224. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    225. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    226. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    227. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    228. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    229. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
    230. var decoder$1;
    231. var Base64 = {
    232. decode: function (a) {
    233. var i;
    234. if (decoder$1 === undefined) {
    235. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    236. var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
    237. decoder$1 = Object.create(null);
    238. for (i = 0; i < 64; ++i) {
    239. decoder$1[b64.charAt(i)] = i;
    240. }
    241. for (i = 0; i < ignore.length; ++i) {
    242. decoder$1[ignore.charAt(i)] = -1;
    243. }
    244. }
    245. var out = [];
    246. var bits = 0;
    247. var char_count = 0;
    248. for (i = 0; i < a.length; ++i) {
    249. var c = a.charAt(i);
    250. if (c == "=") {
    251. break;
    252. }
    253. c = decoder$1[c];
    254. if (c == -1) {
    255. continue;
    256. }
    257. if (c === undefined) {
    258. throw new Error("Illegal character at offset " + i);
    259. }
    260. bits |= c;
    261. if (++char_count >= 4) {
    262. out[out.length] = (bits >> 16);
    263. out[out.length] = (bits >> 8) & 0xFF;
    264. out[out.length] = bits & 0xFF;
    265. bits = 0;
    266. char_count = 0;
    267. }
    268. else {
    269. bits <<= 6;
    270. }
    271. }
    272. switch (char_count) {
    273. case 1:
    274. throw new Error("Base64 encoding incomplete: at least 2 bits missing");
    275. case 2:
    276. out[out.length] = (bits >> 10);
    277. break;
    278. case 3:
    279. out[out.length] = (bits >> 16);
    280. out[out.length] = (bits >> 8) & 0xFF;
    281. break;
    282. }
    283. return out;
    284. },
    285. re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
    286. unarmor: function (a) {
    287. var m = Base64.re.exec(a);
    288. if (m) {
    289. if (m[1]) {
    290. a = m[1];
    291. }
    292. else if (m[2]) {
    293. a = m[2];
    294. }
    295. else {
    296. throw new Error("RegExp out of sync");
    297. }
    298. }
    299. return Base64.decode(a);
    300. }
    301. };
    302. // Big integer base-10 printing library
    303. // Copyright (c) 2014 Lapo Luchini
    304. // Permission to use, copy, modify, and/or distribute this software for any
    305. // purpose with or without fee is hereby granted, provided that the above
    306. // copyright notice and this permission notice appear in all copies.
    307. //
    308. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    309. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    310. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    311. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    312. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    313. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    314. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    315. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
    316. var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
    317. var Int10 = /** @class */ (function () {
    318. function Int10(value) {
    319. this.buf = [+value || 0];
    320. }
    321. Int10.prototype.mulAdd = function (m, c) {
    322. // assert(m <= 256)
    323. var b = this.buf;
    324. var l = b.length;
    325. var i;
    326. var t;
    327. for (i = 0; i < l; ++i) {
    328. t = b[i] * m + c;
    329. if (t < max) {
    330. c = 0;
    331. }
    332. else {
    333. c = 0 | (t / max);
    334. t -= c * max;
    335. }
    336. b[i] = t;
    337. }
    338. if (c > 0) {
    339. b[i] = c;
    340. }
    341. };
    342. Int10.prototype.sub = function (c) {
    343. // assert(m <= 256)
    344. var b = this.buf;
    345. var l = b.length;
    346. var i;
    347. var t;
    348. for (i = 0; i < l; ++i) {
    349. t = b[i] - c;
    350. if (t < 0) {
    351. t += max;
    352. c = 1;
    353. }
    354. else {
    355. c = 0;
    356. }
    357. b[i] = t;
    358. }
    359. while (b[b.length - 1] === 0) {
    360. b.pop();
    361. }
    362. };
    363. Int10.prototype.toString = function (base) {
    364. if ((base || 10) != 10) {
    365. throw new Error("only base 10 is supported");
    366. }
    367. var b = this.buf;
    368. var s = b[b.length - 1].toString();
    369. for (var i = b.length - 2; i >= 0; --i) {
    370. s += (max + b[i]).toString().substring(1);
    371. }
    372. return s;
    373. };
    374. Int10.prototype.valueOf = function () {
    375. var b = this.buf;
    376. var v = 0;
    377. for (var i = b.length - 1; i >= 0; --i) {
    378. v = v * max + b[i];
    379. }
    380. return v;
    381. };
    382. Int10.prototype.simplify = function () {
    383. var b = this.buf;
    384. return (b.length == 1) ? b[0] : this;
    385. };
    386. return Int10;
    387. }());
    388. // ASN.1 JavaScript decoder
    389. var ellipsis = "\u2026";
    390. 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)?)?$/;
    391. 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)?)?$/;
    392. function stringCut(str, len) {
    393. if (str.length > len) {
    394. str = str.substring(0, len) + ellipsis;
    395. }
    396. return str;
    397. }
    398. var Stream = /** @class */ (function () {
    399. function Stream(enc, pos) {
    400. this.hexDigits = "0123456789ABCDEF";
    401. if (enc instanceof Stream) {
    402. this.enc = enc.enc;
    403. this.pos = enc.pos;
    404. }
    405. else {
    406. // enc should be an array or a binary string
    407. this.enc = enc;
    408. this.pos = pos;
    409. }
    410. }
    411. Stream.prototype.get = function (pos) {
    412. if (pos === undefined) {
    413. pos = this.pos++;
    414. }
    415. if (pos >= this.enc.length) {
    416. throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
    417. }
    418. return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
    419. };
    420. Stream.prototype.hexByte = function (b) {
    421. return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
    422. };
    423. Stream.prototype.hexDump = function (start, end, raw) {
    424. var s = "";
    425. for (var i = start; i < end; ++i) {
    426. s += this.hexByte(this.get(i));
    427. if (raw !== true) {
    428. switch (i & 0xF) {
    429. case 0x7:
    430. s += " ";
    431. break;
    432. case 0xF:
    433. s += "\n";
    434. break;
    435. default:
    436. s += " ";
    437. }
    438. }
    439. }
    440. return s;
    441. };
    442. Stream.prototype.isASCII = function (start, end) {
    443. for (var i = start; i < end; ++i) {
    444. var c = this.get(i);
    445. if (c < 32 || c > 176) {
    446. return false;
    447. }
    448. }
    449. return true;
    450. };
    451. Stream.prototype.parseStringISO = function (start, end) {
    452. var s = "";
    453. for (var i = start; i < end; ++i) {
    454. s += String.fromCharCode(this.get(i));
    455. }
    456. return s;
    457. };
    458. Stream.prototype.parseStringUTF = function (start, end) {
    459. var s = "";
    460. for (var i = start; i < end;) {
    461. var c = this.get(i++);
    462. if (c < 128) {
    463. s += String.fromCharCode(c);
    464. }
    465. else if ((c > 191) && (c < 224)) {
    466. s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
    467. }
    468. else {
    469. s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
    470. }
    471. }
    472. return s;
    473. };
    474. Stream.prototype.parseStringBMP = function (start, end) {
    475. var str = "";
    476. var hi;
    477. var lo;
    478. for (var i = start; i < end;) {
    479. hi = this.get(i++);
    480. lo = this.get(i++);
    481. str += String.fromCharCode((hi << 8) | lo);
    482. }
    483. return str;
    484. };
    485. Stream.prototype.parseTime = function (start, end, shortYear) {
    486. var s = this.parseStringISO(start, end);
    487. var m = (shortYear ? reTimeS : reTimeL).exec(s);
    488. if (!m) {
    489. return "Unrecognized time: " + s;
    490. }
    491. if (shortYear) {
    492. // to avoid querying the timer, use the fixed range [1970, 2069]
    493. // it will conform with ITU X.400 [-10, +40] sliding window until 2030
    494. m[1] = +m[1];
    495. m[1] += (+m[1] < 70) ? 2000 : 1900;
    496. }
    497. s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
    498. if (m[5]) {
    499. s += ":" + m[5];
    500. if (m[6]) {
    501. s += ":" + m[6];
    502. if (m[7]) {
    503. s += "." + m[7];
    504. }
    505. }
    506. }
    507. if (m[8]) {
    508. s += " UTC";
    509. if (m[8] != "Z") {
    510. s += m[8];
    511. if (m[9]) {
    512. s += ":" + m[9];
    513. }
    514. }
    515. }
    516. return s;
    517. };
    518. Stream.prototype.parseInteger = function (start, end) {
    519. var v = this.get(start);
    520. var neg = (v > 127);
    521. var pad = neg ? 255 : 0;
    522. var len;
    523. var s = "";
    524. // skip unuseful bits (not allowed in DER)
    525. while (v == pad && ++start < end) {
    526. v = this.get(start);
    527. }
    528. len = end - start;
    529. if (len === 0) {
    530. return neg ? -1 : 0;
    531. }
    532. // show bit length of huge integers
    533. if (len > 4) {
    534. s = v;
    535. len <<= 3;
    536. while (((+s ^ pad) & 0x80) == 0) {
    537. s = +s << 1;
    538. --len;
    539. }
    540. s = "(" + len + " bit)\n";
    541. }
    542. // decode the integer
    543. if (neg) {
    544. v = v - 256;
    545. }
    546. var n = new Int10(v);
    547. for (var i = start + 1; i < end; ++i) {
    548. n.mulAdd(256, this.get(i));
    549. }
    550. return s + n.toString();
    551. };
    552. Stream.prototype.parseBitString = function (start, end, maxLength) {
    553. var unusedBit = this.get(start);
    554. var lenBit = ((end - start - 1) << 3) - unusedBit;
    555. var intro = "(" + lenBit + " bit)\n";
    556. var s = "";
    557. for (var i = start + 1; i < end; ++i) {
    558. var b = this.get(i);
    559. var skip = (i == end - 1) ? unusedBit : 0;
    560. for (var j = 7; j >= skip; --j) {
    561. s += (b >> j) & 1 ? "1" : "0";
    562. }
    563. if (s.length > maxLength) {
    564. return intro + stringCut(s, maxLength);
    565. }
    566. }
    567. return intro + s;
    568. };
    569. Stream.prototype.parseOctetString = function (start, end, maxLength) {
    570. if (this.isASCII(start, end)) {
    571. return stringCut(this.parseStringISO(start, end), maxLength);
    572. }
    573. var len = end - start;
    574. var s = "(" + len + " byte)\n";
    575. maxLength /= 2; // we work in bytes
    576. if (len > maxLength) {
    577. end = start + maxLength;
    578. }
    579. for (var i = start; i < end; ++i) {
    580. s += this.hexByte(this.get(i));
    581. }
    582. if (len > maxLength) {
    583. s += ellipsis;
    584. }
    585. return s;
    586. };
    587. Stream.prototype.parseOID = function (start, end, maxLength) {
    588. var s = "";
    589. var n = new Int10();
    590. var bits = 0;
    591. for (var i = start; i < end; ++i) {
    592. var v = this.get(i);
    593. n.mulAdd(128, v & 0x7F);
    594. bits += 7;
    595. if (!(v & 0x80)) { // finished
    596. if (s === "") {
    597. n = n.simplify();
    598. if (n instanceof Int10) {
    599. n.sub(80);
    600. s = "2." + n.toString();
    601. }
    602. else {
    603. var m = n < 80 ? n < 40 ? 0 : 1 : 2;
    604. s = m + "." + (n - m * 40);
    605. }
    606. }
    607. else {
    608. s += "." + n.toString();
    609. }
    610. if (s.length > maxLength) {
    611. return stringCut(s, maxLength);
    612. }
    613. n = new Int10();
    614. bits = 0;
    615. }
    616. }
    617. if (bits > 0) {
    618. s += ".incomplete";
    619. }
    620. return s;
    621. };
    622. return Stream;
    623. }());
    624. var ASN1 = /** @class */ (function () {
    625. function ASN1(stream, header, length, tag, sub) {
    626. if (!(tag instanceof ASN1Tag)) {
    627. throw new Error("Invalid tag value.");
    628. }
    629. this.stream = stream;
    630. this.header = header;
    631. this.length = length;
    632. this.tag = tag;
    633. this.sub = sub;
    634. }
    635. ASN1.prototype.typeName = function () {
    636. switch (this.tag.tagClass) {
    637. case 0: // universal
    638. switch (this.tag.tagNumber) {
    639. case 0x00:
    640. return "EOC";
    641. case 0x01:
    642. return "BOOLEAN";
    643. case 0x02:
    644. return "INTEGER";
    645. case 0x03:
    646. return "BIT_STRING";
    647. case 0x04:
    648. return "OCTET_STRING";
    649. case 0x05:
    650. return "NULL";
    651. case 0x06:
    652. return "OBJECT_IDENTIFIER";
    653. case 0x07:
    654. return "ObjectDescriptor";
    655. case 0x08:
    656. return "EXTERNAL";
    657. case 0x09:
    658. return "REAL";
    659. case 0x0A:
    660. return "ENUMERATED";
    661. case 0x0B:
    662. return "EMBEDDED_PDV";
    663. case 0x0C:
    664. return "UTF8String";
    665. case 0x10:
    666. return "SEQUENCE";
    667. case 0x11:
    668. return "SET";
    669. case 0x12:
    670. return "NumericString";
    671. case 0x13:
    672. return "PrintableString"; // ASCII subset
    673. case 0x14:
    674. return "TeletexString"; // aka T61String
    675. case 0x15:
    676. return "VideotexString";
    677. case 0x16:
    678. return "IA5String"; // ASCII
    679. case 0x17:
    680. return "UTCTime";
    681. case 0x18:
    682. return "GeneralizedTime";
    683. case 0x19:
    684. return "GraphicString";
    685. case 0x1A:
    686. return "VisibleString"; // ASCII subset
    687. case 0x1B:
    688. return "GeneralString";
    689. case 0x1C:
    690. return "UniversalString";
    691. case 0x1E:
    692. return "BMPString";
    693. }
    694. return "Universal_" + this.tag.tagNumber.toString();
    695. case 1:
    696. return "Application_" + this.tag.tagNumber.toString();
    697. case 2:
    698. return "[" + this.tag.tagNumber.toString() + "]"; // Context
    699. case 3:
    700. return "Private_" + this.tag.tagNumber.toString();
    701. }
    702. };
    703. ASN1.prototype.content = function (maxLength) {
    704. if (this.tag === undefined) {
    705. return null;
    706. }
    707. if (maxLength === undefined) {
    708. maxLength = Infinity;
    709. }
    710. var content = this.posContent();
    711. var len = Math.abs(this.length);
    712. if (!this.tag.isUniversal()) {
    713. if (this.sub !== null) {
    714. return "(" + this.sub.length + " elem)";
    715. }
    716. return this.stream.parseOctetString(content, content + len, maxLength);
    717. }
    718. switch (this.tag.tagNumber) {
    719. case 0x01: // BOOLEAN
    720. return (this.stream.get(content) === 0) ? "false" : "true";
    721. case 0x02: // INTEGER
    722. return this.stream.parseInteger(content, content + len);
    723. case 0x03: // BIT_STRING
    724. return this.sub ? "(" + this.sub.length + " elem)" :
    725. this.stream.parseBitString(content, content + len, maxLength);
    726. case 0x04: // OCTET_STRING
    727. return this.sub ? "(" + this.sub.length + " elem)" :
    728. this.stream.parseOctetString(content, content + len, maxLength);
    729. // case 0x05: // NULL
    730. case 0x06: // OBJECT_IDENTIFIER
    731. return this.stream.parseOID(content, content + len, maxLength);
    732. // case 0x07: // ObjectDescriptor
    733. // case 0x08: // EXTERNAL
    734. // case 0x09: // REAL
    735. // case 0x0A: // ENUMERATED
    736. // case 0x0B: // EMBEDDED_PDV
    737. case 0x10: // SEQUENCE
    738. case 0x11: // SET
    739. if (this.sub !== null) {
    740. return "(" + this.sub.length + " elem)";
    741. }
    742. else {
    743. return "(no elem)";
    744. }
    745. case 0x0C: // UTF8String
    746. return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
    747. case 0x12: // NumericString
    748. case 0x13: // PrintableString
    749. case 0x14: // TeletexString
    750. case 0x15: // VideotexString
    751. case 0x16: // IA5String
    752. // case 0x19: // GraphicString
    753. case 0x1A: // VisibleString
    754. // case 0x1B: // GeneralString
    755. // case 0x1C: // UniversalString
    756. return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
    757. case 0x1E: // BMPString
    758. return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
    759. case 0x17: // UTCTime
    760. case 0x18: // GeneralizedTime
    761. return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
    762. }
    763. return null;
    764. };
    765. ASN1.prototype.toString = function () {
    766. return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
    767. };
    768. ASN1.prototype.toPrettyString = function (indent) {
    769. if (indent === undefined) {
    770. indent = "";
    771. }
    772. var s = indent + this.typeName() + " @" + this.stream.pos;
    773. if (this.length >= 0) {
    774. s += "+";
    775. }
    776. s += this.length;
    777. if (this.tag.tagConstructed) {
    778. s += " (constructed)";
    779. }
    780. else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
    781. s += " (encapsulates)";
    782. }
    783. s += "\n";
    784. if (this.sub !== null) {
    785. indent += " ";
    786. for (var i = 0, max = this.sub.length; i < max; ++i) {
    787. s += this.sub[i].toPrettyString(indent);
    788. }
    789. }
    790. return s;
    791. };
    792. ASN1.prototype.posStart = function () {
    793. return this.stream.pos;
    794. };
    795. ASN1.prototype.posContent = function () {
    796. return this.stream.pos + this.header;
    797. };
    798. ASN1.prototype.posEnd = function () {
    799. return this.stream.pos + this.header + Math.abs(this.length);
    800. };
    801. ASN1.prototype.toHexString = function () {
    802. return this.stream.hexDump(this.posStart(), this.posEnd(), true);
    803. };
    804. ASN1.decodeLength = function (stream) {
    805. var buf = stream.get();
    806. var len = buf & 0x7F;
    807. if (len == buf) {
    808. return len;
    809. }
    810. // no reason to use Int10, as it would be a huge buffer anyways
    811. if (len > 6) {
    812. throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
    813. }
    814. if (len === 0) {
    815. return null;
    816. } // undefined
    817. buf = 0;
    818. for (var i = 0; i < len; ++i) {
    819. buf = (buf * 256) + stream.get();
    820. }
    821. return buf;
    822. };
    823. /**
    824. * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
    825. * @returns {string}
    826. * @public
    827. */
    828. ASN1.prototype.getHexStringValue = function () {
    829. var hexString = this.toHexString();
    830. var offset = this.header * 2;
    831. var length = this.length * 2;
    832. return hexString.substr(offset, length);
    833. };
    834. ASN1.decode = function (str) {
    835. var stream;
    836. if (!(str instanceof Stream)) {
    837. stream = new Stream(str, 0);
    838. }
    839. else {
    840. stream = str;
    841. }
    842. var streamStart = new Stream(stream);
    843. var tag = new ASN1Tag(stream);
    844. var len = ASN1.decodeLength(stream);
    845. var start = stream.pos;
    846. var header = start - streamStart.pos;
    847. var sub = null;
    848. var getSub = function () {
    849. var ret = [];
    850. if (len !== null) {
    851. // definite length
    852. var end = start + len;
    853. while (stream.pos < end) {
    854. ret[ret.length] = ASN1.decode(stream);
    855. }
    856. if (stream.pos != end) {
    857. throw new Error("Content size is not correct for container starting at offset " + start);
    858. }
    859. }
    860. else {
    861. // undefined length
    862. try {
    863. for (;;) {
    864. var s = ASN1.decode(stream);
    865. if (s.tag.isEOC()) {
    866. break;
    867. }
    868. ret[ret.length] = s;
    869. }
    870. len = start - stream.pos; // undefined lengths are represented as negative values
    871. }
    872. catch (e) {
    873. throw new Error("Exception while decoding undefined length content: " + e);
    874. }
    875. }
    876. return ret;
    877. };
    878. if (tag.tagConstructed) {
    879. // must have valid content
    880. sub = getSub();
    881. }
    882. else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
    883. // sometimes BitString and OctetString are used to encapsulate ASN.1
    884. try {
    885. if (tag.tagNumber == 0x03) {
    886. if (stream.get() != 0) {
    887. throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
    888. }
    889. }
    890. sub = getSub();
    891. for (var i = 0; i < sub.length; ++i) {
    892. if (sub[i].tag.isEOC()) {
    893. throw new Error("EOC is not supposed to be actual content.");
    894. }
    895. }
    896. }
    897. catch (e) {
    898. // but silently ignore when they don't
    899. sub = null;
    900. }
    901. }
    902. if (sub === null) {
    903. if (len === null) {
    904. throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
    905. }
    906. stream.pos = start + Math.abs(len);
    907. }
    908. return new ASN1(streamStart, header, len, tag, sub);
    909. };
    910. return ASN1;
    911. }());
    912. var ASN1Tag = /** @class */ (function () {
    913. function ASN1Tag(stream) {
    914. var buf = stream.get();
    915. this.tagClass = buf >> 6;
    916. this.tagConstructed = ((buf & 0x20) !== 0);
    917. this.tagNumber = buf & 0x1F;
    918. if (this.tagNumber == 0x1F) { // long tag
    919. var n = new Int10();
    920. do {
    921. buf = stream.get();
    922. n.mulAdd(128, buf & 0x7F);
    923. } while (buf & 0x80);
    924. this.tagNumber = n.simplify();
    925. }
    926. }
    927. ASN1Tag.prototype.isUniversal = function () {
    928. return this.tagClass === 0x00;
    929. };
    930. ASN1Tag.prototype.isEOC = function () {
    931. return this.tagClass === 0x00 && this.tagNumber === 0x00;
    932. };
    933. return ASN1Tag;
    934. }());
    935. // Copyright (c) 2005 Tom Wu
    936. // Bits per digit
    937. var dbits;
    938. // JavaScript engine analysis
    939. var canary = 0xdeadbeefcafe;
    940. var j_lm = ((canary & 0xffffff) == 0xefcafe);
    941. //#region
    942. 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];
    943. var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
    944. //#endregion
    945. // (public) Constructor
    946. var BigInteger = /** @class */ (function () {
    947. function BigInteger(a, b, c) {
    948. if (a != null) {
    949. if ("number" == typeof a) {
    950. this.fromNumber(a, b, c);
    951. }
    952. else if (b == null && "string" != typeof a) {
    953. this.fromString(a, 256);
    954. }
    955. else {
    956. this.fromString(a, b);
    957. }
    958. }
    959. }
    960. //#region PUBLIC
    961. // BigInteger.prototype.toString = bnToString;
    962. // (public) return string representation in given radix
    963. BigInteger.prototype.toString = function (b) {
    964. if (this.s < 0) {
    965. return "-" + this.negate().toString(b);
    966. }
    967. var k;
    968. if (b == 16) {
    969. k = 4;
    970. }
    971. else if (b == 8) {
    972. k = 3;
    973. }
    974. else if (b == 2) {
    975. k = 1;
    976. }
    977. else if (b == 32) {
    978. k = 5;
    979. }
    980. else if (b == 4) {
    981. k = 2;
    982. }
    983. else {
    984. return this.toRadix(b);
    985. }
    986. var km = (1 << k) - 1;
    987. var d;
    988. var m = false;
    989. var r = "";
    990. var i = this.t;
    991. var p = this.DB - (i * this.DB) % k;
    992. if (i-- > 0) {
    993. if (p < this.DB && (d = this[i] >> p) > 0) {
    994. m = true;
    995. r = int2char(d);
    996. }
    997. while (i >= 0) {
    998. if (p < k) {
    999. d = (this[i] & ((1 << p) - 1)) << (k - p);
    1000. d |= this[--i] >> (p += this.DB - k);
    1001. }
    1002. else {
    1003. d = (this[i] >> (p -= k)) & km;
    1004. if (p <= 0) {
    1005. p += this.DB;
    1006. --i;
    1007. }
    1008. }
    1009. if (d > 0) {
    1010. m = true;
    1011. }
    1012. if (m) {
    1013. r += int2char(d);
    1014. }
    1015. }
    1016. }
    1017. return m ? r : "0";
    1018. };
    1019. // BigInteger.prototype.negate = bnNegate;
    1020. // (public) -this
    1021. BigInteger.prototype.negate = function () {
    1022. var r = nbi();
    1023. BigInteger.ZERO.subTo(this, r);
    1024. return r;
    1025. };
    1026. // BigInteger.prototype.abs = bnAbs;
    1027. // (public) |this|
    1028. BigInteger.prototype.abs = function () {
    1029. return (this.s < 0) ? this.negate() : this;
    1030. };
    1031. // BigInteger.prototype.compareTo = bnCompareTo;
    1032. // (public) return + if this > a, - if this < a, 0 if equal
    1033. BigInteger.prototype.compareTo = function (a) {
    1034. var r = this.s - a.s;
    1035. if (r != 0) {
    1036. return r;
    1037. }
    1038. var i = this.t;
    1039. r = i - a.t;
    1040. if (r != 0) {
    1041. return (this.s < 0) ? -r : r;
    1042. }
    1043. while (--i >= 0) {
    1044. if ((r = this[i] - a[i]) != 0) {
    1045. return r;
    1046. }
    1047. }
    1048. return 0;
    1049. };
    1050. // BigInteger.prototype.bitLength = bnBitLength;
    1051. // (public) return the number of bits in "this"
    1052. BigInteger.prototype.bitLength = function () {
    1053. if (this.t <= 0) {
    1054. return 0;
    1055. }
    1056. return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
    1057. };
    1058. // BigInteger.prototype.mod = bnMod;
    1059. // (public) this mod a
    1060. BigInteger.prototype.mod = function (a) {
    1061. var r = nbi();
    1062. this.abs().divRemTo(a, null, r);
    1063. if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
    1064. a.subTo(r, r);
    1065. }
    1066. return r;
    1067. };
    1068. // BigInteger.prototype.modPowInt = bnModPowInt;
    1069. // (public) this^e % m, 0 <= e < 2^32
    1070. BigInteger.prototype.modPowInt = function (e, m) {
    1071. var z;
    1072. if (e < 256 || m.isEven()) {
    1073. z = new Classic(m);
    1074. }
    1075. else {
    1076. z = new Montgomery(m);
    1077. }
    1078. return this.exp(e, z);
    1079. };
    1080. // BigInteger.prototype.clone = bnClone;
    1081. // (public)
    1082. BigInteger.prototype.clone = function () {
    1083. var r = nbi();
    1084. this.copyTo(r);
    1085. return r;
    1086. };
    1087. // BigInteger.prototype.intValue = bnIntValue;
    1088. // (public) return value as integer
    1089. BigInteger.prototype.intValue = function () {
    1090. if (this.s < 0) {
    1091. if (this.t == 1) {
    1092. return this[0] - this.DV;
    1093. }
    1094. else if (this.t == 0) {
    1095. return -1;
    1096. }
    1097. }
    1098. else if (this.t == 1) {
    1099. return this[0];
    1100. }
    1101. else if (this.t == 0) {
    1102. return 0;
    1103. }
    1104. // assumes 16 < DB < 32
    1105. return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
    1106. };
    1107. // BigInteger.prototype.byteValue = bnByteValue;
    1108. // (public) return value as byte
    1109. BigInteger.prototype.byteValue = function () {
    1110. return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
    1111. };
    1112. // BigInteger.prototype.shortValue = bnShortValue;
    1113. // (public) return value as short (assumes DB>=16)
    1114. BigInteger.prototype.shortValue = function () {
    1115. return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
    1116. };
    1117. // BigInteger.prototype.signum = bnSigNum;
    1118. // (public) 0 if this == 0, 1 if this > 0
    1119. BigInteger.prototype.signum = function () {
    1120. if (this.s < 0) {
    1121. return -1;
    1122. }
    1123. else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
    1124. return 0;
    1125. }
    1126. else {
    1127. return 1;
    1128. }
    1129. };
    1130. // BigInteger.prototype.toByteArray = bnToByteArray;
    1131. // (public) convert to bigendian byte array
    1132. BigInteger.prototype.toByteArray = function () {
    1133. var i = this.t;
    1134. var r = [];
    1135. r[0] = this.s;
    1136. var p = this.DB - (i * this.DB) % 8;
    1137. var d;
    1138. var k = 0;
    1139. if (i-- > 0) {
    1140. if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
    1141. r[k++] = d | (this.s << (this.DB - p));
    1142. }
    1143. while (i >= 0) {
    1144. if (p < 8) {
    1145. d = (this[i] & ((1 << p) - 1)) << (8 - p);
    1146. d |= this[--i] >> (p += this.DB - 8);
    1147. }
    1148. else {
    1149. d = (this[i] >> (p -= 8)) & 0xff;
    1150. if (p <= 0) {
    1151. p += this.DB;
    1152. --i;
    1153. }
    1154. }
    1155. if ((d & 0x80) != 0) {
    1156. d |= -256;
    1157. }
    1158. if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
    1159. ++k;
    1160. }
    1161. if (k > 0 || d != this.s) {
    1162. r[k++] = d;
    1163. }
    1164. }
    1165. }
    1166. return r;
    1167. };
    1168. // BigInteger.prototype.equals = bnEquals;
    1169. BigInteger.prototype.equals = function (a) {
    1170. return (this.compareTo(a) == 0);
    1171. };
    1172. // BigInteger.prototype.min = bnMin;
    1173. BigInteger.prototype.min = function (a) {
    1174. return (this.compareTo(a) < 0) ? this : a;
    1175. };
    1176. // BigInteger.prototype.max = bnMax;
    1177. BigInteger.prototype.max = function (a) {
    1178. return (this.compareTo(a) > 0) ? this : a;
    1179. };
    1180. // BigInteger.prototype.and = bnAnd;
    1181. BigInteger.prototype.and = function (a) {
    1182. var r = nbi();
    1183. this.bitwiseTo(a, op_and, r);
    1184. return r;
    1185. };
    1186. // BigInteger.prototype.or = bnOr;
    1187. BigInteger.prototype.or = function (a) {
    1188. var r = nbi();
    1189. this.bitwiseTo(a, op_or, r);
    1190. return r;
    1191. };
    1192. // BigInteger.prototype.xor = bnXor;
    1193. BigInteger.prototype.xor = function (a) {
    1194. var r = nbi();
    1195. this.bitwiseTo(a, op_xor, r);
    1196. return r;
    1197. };
    1198. // BigInteger.prototype.andNot = bnAndNot;
    1199. BigInteger.prototype.andNot = function (a) {
    1200. var r = nbi();
    1201. this.bitwiseTo(a, op_andnot, r);
    1202. return r;
    1203. };
    1204. // BigInteger.prototype.not = bnNot;
    1205. // (public) ~this
    1206. BigInteger.prototype.not = function () {
    1207. var r = nbi();
    1208. for (var i = 0; i < this.t; ++i) {
    1209. r[i] = this.DM & ~this[i];
    1210. }
    1211. r.t = this.t;
    1212. r.s = ~this.s;
    1213. return r;
    1214. };
    1215. // BigInteger.prototype.shiftLeft = bnShiftLeft;
    1216. // (public) this << n
    1217. BigInteger.prototype.shiftLeft = function (n) {
    1218. var r = nbi();
    1219. if (n < 0) {
    1220. this.rShiftTo(-n, r);
    1221. }
    1222. else {
    1223. this.lShiftTo(n, r);
    1224. }
    1225. return r;
    1226. };
    1227. // BigInteger.prototype.shiftRight = bnShiftRight;
    1228. // (public) this >> n
    1229. BigInteger.prototype.shiftRight = function (n) {
    1230. var r = nbi();
    1231. if (n < 0) {
    1232. this.lShiftTo(-n, r);
    1233. }
    1234. else {
    1235. this.rShiftTo(n, r);
    1236. }
    1237. return r;
    1238. };
    1239. // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
    1240. // (public) returns index of lowest 1-bit (or -1 if none)
    1241. BigInteger.prototype.getLowestSetBit = function () {
    1242. for (var i = 0; i < this.t; ++i) {
    1243. if (this[i] != 0) {
    1244. return i * this.DB + lbit(this[i]);
    1245. }
    1246. }
    1247. if (this.s < 0) {
    1248. return this.t * this.DB;
    1249. }
    1250. return -1;
    1251. };
    1252. // BigInteger.prototype.bitCount = bnBitCount;
    1253. // (public) return number of set bits
    1254. BigInteger.prototype.bitCount = function () {
    1255. var r = 0;
    1256. var x = this.s & this.DM;
    1257. for (var i = 0; i < this.t; ++i) {
    1258. r += cbit(this[i] ^ x);
    1259. }
    1260. return r;
    1261. };
    1262. // BigInteger.prototype.testBit = bnTestBit;
    1263. // (public) true iff nth bit is set
    1264. BigInteger.prototype.testBit = function (n) {
    1265. var j = Math.floor(n / this.DB);
    1266. if (j >= this.t) {
    1267. return (this.s != 0);
    1268. }
    1269. return ((this[j] & (1 << (n % this.DB))) != 0);
    1270. };
    1271. // BigInteger.prototype.setBit = bnSetBit;
    1272. // (public) this | (1<
    1273. BigInteger.prototype.setBit = function (n) {
    1274. return this.changeBit(n, op_or);
    1275. };
    1276. // BigInteger.prototype.clearBit = bnClearBit;
    1277. // (public) this & ~(1<
    1278. BigInteger.prototype.clearBit = function (n) {
    1279. return this.changeBit(n, op_andnot);
    1280. };
    1281. // BigInteger.prototype.flipBit = bnFlipBit;
    1282. // (public) this ^ (1<
    1283. BigInteger.prototype.flipBit = function (n) {
    1284. return this.changeBit(n, op_xor);
    1285. };
    1286. // BigInteger.prototype.add = bnAdd;
    1287. // (public) this + a
    1288. BigInteger.prototype.add = function (a) {
    1289. var r = nbi();
    1290. this.addTo(a, r);
    1291. return r;
    1292. };
    1293. // BigInteger.prototype.subtract = bnSubtract;
    1294. // (public) this - a
    1295. BigInteger.prototype.subtract = function (a) {
    1296. var r = nbi();
    1297. this.subTo(a, r);
    1298. return r;
    1299. };
    1300. // BigInteger.prototype.multiply = bnMultiply;
    1301. // (public) this * a
    1302. BigInteger.prototype.multiply = function (a) {
    1303. var r = nbi();
    1304. this.multiplyTo(a, r);
    1305. return r;
    1306. };
    1307. // BigInteger.prototype.divide = bnDivide;
    1308. // (public) this / a
    1309. BigInteger.prototype.divide = function (a) {
    1310. var r = nbi();
    1311. this.divRemTo(a, r, null);
    1312. return r;
    1313. };
    1314. // BigInteger.prototype.remainder = bnRemainder;
    1315. // (public) this % a
    1316. BigInteger.prototype.remainder = function (a) {
    1317. var r = nbi();
    1318. this.divRemTo(a, null, r);
    1319. return r;
    1320. };
    1321. // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
    1322. // (public) [this/a,this%a]
    1323. BigInteger.prototype.divideAndRemainder = function (a) {
    1324. var q = nbi();
    1325. var r = nbi();
    1326. this.divRemTo(a, q, r);
    1327. return [q, r];
    1328. };
    1329. // BigInteger.prototype.modPow = bnModPow;
    1330. // (public) this^e % m (HAC 14.85)
    1331. BigInteger.prototype.modPow = function (e, m) {
    1332. var i = e.bitLength();
    1333. var k;
    1334. var r = nbv(1);
    1335. var z;
    1336. if (i <= 0) {
    1337. return r;
    1338. }
    1339. else if (i < 18) {
    1340. k = 1;
    1341. }
    1342. else if (i < 48) {
    1343. k = 3;
    1344. }
    1345. else if (i < 144) {
    1346. k = 4;
    1347. }
    1348. else if (i < 768) {
    1349. k = 5;
    1350. }
    1351. else {
    1352. k = 6;
    1353. }
    1354. if (i < 8) {
    1355. z = new Classic(m);
    1356. }
    1357. else if (m.isEven()) {
    1358. z = new Barrett(m);
    1359. }
    1360. else {
    1361. z = new Montgomery(m);
    1362. }
    1363. // precomputation
    1364. var g = [];
    1365. var n = 3;
    1366. var k1 = k - 1;
    1367. var km = (1 << k) - 1;
    1368. g[1] = z.convert(this);
    1369. if (k > 1) {
    1370. var g2 = nbi();
    1371. z.sqrTo(g[1], g2);
    1372. while (n <= km) {
    1373. g[n] = nbi();
    1374. z.mulTo(g2, g[n - 2], g[n]);
    1375. n += 2;
    1376. }
    1377. }
    1378. var j = e.t - 1;
    1379. var w;
    1380. var is1 = true;
    1381. var r2 = nbi();
    1382. var t;
    1383. i = nbits(e[j]) - 1;
    1384. while (j >= 0) {
    1385. if (i >= k1) {
    1386. w = (e[j] >> (i - k1)) & km;
    1387. }
    1388. else {
    1389. w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
    1390. if (j > 0) {
    1391. w |= e[j - 1] >> (this.DB + i - k1);
    1392. }
    1393. }
    1394. n = k;
    1395. while ((w & 1) == 0) {
    1396. w >>= 1;
    1397. --n;
    1398. }
    1399. if ((i -= n) < 0) {
    1400. i += this.DB;
    1401. --j;
    1402. }
    1403. if (is1) { // ret == 1, don't bother squaring or multiplying it
    1404. g[w].copyTo(r);
    1405. is1 = false;
    1406. }
    1407. else {
    1408. while (n > 1) {
    1409. z.sqrTo(r, r2);
    1410. z.sqrTo(r2, r);
    1411. n -= 2;
    1412. }
    1413. if (n > 0) {
    1414. z.sqrTo(r, r2);
    1415. }
    1416. else {
    1417. t = r;
    1418. r = r2;
    1419. r2 = t;
    1420. }
    1421. z.mulTo(r2, g[w], r);
    1422. }
    1423. while (j >= 0 && (e[j] & (1 << i)) == 0) {
    1424. z.sqrTo(r, r2);
    1425. t = r;
    1426. r = r2;
    1427. r2 = t;
    1428. if (--i < 0) {
    1429. i = this.DB - 1;
    1430. --j;
    1431. }
    1432. }
    1433. }
    1434. return z.revert(r);
    1435. };
    1436. // BigInteger.prototype.modInverse = bnModInverse;
    1437. // (public) 1/this % m (HAC 14.61)
    1438. BigInteger.prototype.modInverse = function (m) {
    1439. var ac = m.isEven();
    1440. if ((this.isEven() && ac) || m.signum() == 0) {
    1441. return BigInteger.ZERO;
    1442. }
    1443. var u = m.clone();
    1444. var v = this.clone();
    1445. var a = nbv(1);
    1446. var b = nbv(0);
    1447. var c = nbv(0);
    1448. var d = nbv(1);
    1449. while (u.signum() != 0) {
    1450. while (u.isEven()) {
    1451. u.rShiftTo(1, u);
    1452. if (ac) {
    1453. if (!a.isEven() || !b.isEven()) {
    1454. a.addTo(this, a);
    1455. b.subTo(m, b);
    1456. }
    1457. a.rShiftTo(1, a);
    1458. }
    1459. else if (!b.isEven()) {
    1460. b.subTo(m, b);
    1461. }
    1462. b.rShiftTo(1, b);
    1463. }
    1464. while (v.isEven()) {
    1465. v.rShiftTo(1, v);
    1466. if (ac) {
    1467. if (!c.isEven() || !d.isEven()) {
    1468. c.addTo(this, c);
    1469. d.subTo(m, d);
    1470. }
    1471. c.rShiftTo(1, c);
    1472. }
    1473. else if (!d.isEven()) {
    1474. d.subTo(m, d);
    1475. }
    1476. d.rShiftTo(1, d);
    1477. }
    1478. if (u.compareTo(v) >= 0) {
    1479. u.subTo(v, u);
    1480. if (ac) {
    1481. a.subTo(c, a);
    1482. }
    1483. b.subTo(d, b);
    1484. }
    1485. else {
    1486. v.subTo(u, v);
    1487. if (ac) {
    1488. c.subTo(a, c);
    1489. }
    1490. d.subTo(b, d);
    1491. }
    1492. }
    1493. if (v.compareTo(BigInteger.ONE) != 0) {
    1494. return BigInteger.ZERO;
    1495. }
    1496. if (d.compareTo(m) >= 0) {
    1497. return d.subtract(m);
    1498. }
    1499. if (d.signum() < 0) {
    1500. d.addTo(m, d);
    1501. }
    1502. else {
    1503. return d;
    1504. }
    1505. if (d.signum() < 0) {
    1506. return d.add(m);
    1507. }
    1508. else {
    1509. return d;
    1510. }
    1511. };
    1512. // BigInteger.prototype.pow = bnPow;
    1513. // (public) this^e
    1514. BigInteger.prototype.pow = function (e) {
    1515. return this.exp(e, new NullExp());
    1516. };
    1517. // BigInteger.prototype.gcd = bnGCD;
    1518. // (public) gcd(this,a) (HAC 14.54)
    1519. BigInteger.prototype.gcd = function (a) {
    1520. var x = (this.s < 0) ? this.negate() : this.clone();
    1521. var y = (a.s < 0) ? a.negate() : a.clone();
    1522. if (x.compareTo(y) < 0) {
    1523. var t = x;
    1524. x = y;
    1525. y = t;
    1526. }
    1527. var i = x.getLowestSetBit();
    1528. var g = y.getLowestSetBit();
    1529. if (g < 0) {
    1530. return x;
    1531. }
    1532. if (i < g) {
    1533. g = i;
    1534. }
    1535. if (g > 0) {
    1536. x.rShiftTo(g, x);
    1537. y.rShiftTo(g, y);
    1538. }
    1539. while (x.signum() > 0) {
    1540. if ((i = x.getLowestSetBit()) > 0) {
    1541. x.rShiftTo(i, x);
    1542. }
    1543. if ((i = y.getLowestSetBit()) > 0) {
    1544. y.rShiftTo(i, y);
    1545. }
    1546. if (x.compareTo(y) >= 0) {
    1547. x.subTo(y, x);
    1548. x.rShiftTo(1, x);
    1549. }
    1550. else {
    1551. y.subTo(x, y);
    1552. y.rShiftTo(1, y);
    1553. }
    1554. }
    1555. if (g > 0) {
    1556. y.lShiftTo(g, y);
    1557. }
    1558. return y;
    1559. };
    1560. // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
    1561. // (public) test primality with certainty >= 1-.5^t
    1562. BigInteger.prototype.isProbablePrime = function (t) {
    1563. var i;
    1564. var x = this.abs();
    1565. if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
    1566. for (i = 0; i < lowprimes.length; ++i) {
    1567. if (x[0] == lowprimes[i]) {
    1568. return true;
    1569. }
    1570. }
    1571. return false;
    1572. }
    1573. if (x.isEven()) {
    1574. return false;
    1575. }
    1576. i = 1;
    1577. while (i < lowprimes.length) {
    1578. var m = lowprimes[i];
    1579. var j = i + 1;
    1580. while (j < lowprimes.length && m < lplim) {
    1581. m *= lowprimes[j++];
    1582. }
    1583. m = x.modInt(m);
    1584. while (i < j) {
    1585. if (m % lowprimes[i++] == 0) {
    1586. return false;
    1587. }
    1588. }
    1589. }
    1590. return x.millerRabin(t);
    1591. };
    1592. //#endregion PUBLIC
    1593. //#region PROTECTED
    1594. // BigInteger.prototype.copyTo = bnpCopyTo;
    1595. // (protected) copy this to r
    1596. BigInteger.prototype.copyTo = function (r) {
    1597. for (var i = this.t - 1; i >= 0; --i) {
    1598. r[i] = this[i];
    1599. }
    1600. r.t = this.t;
    1601. r.s = this.s;
    1602. };
    1603. // BigInteger.prototype.fromInt = bnpFromInt;
    1604. // (protected) set from integer value x, -DV <= x < DV
    1605. BigInteger.prototype.fromInt = function (x) {
    1606. this.t = 1;
    1607. this.s = (x < 0) ? -1 : 0;
    1608. if (x > 0) {
    1609. this[0] = x;
    1610. }
    1611. else if (x < -1) {
    1612. this[0] = x + this.DV;
    1613. }
    1614. else {
    1615. this.t = 0;
    1616. }
    1617. };
    1618. // BigInteger.prototype.fromString = bnpFromString;
    1619. // (protected) set from string and radix
    1620. BigInteger.prototype.fromString = function (s, b) {
    1621. var k;
    1622. if (b == 16) {
    1623. k = 4;
    1624. }
    1625. else if (b == 8) {
    1626. k = 3;
    1627. }
    1628. else if (b == 256) {
    1629. k = 8;
    1630. /* byte array */
    1631. }
    1632. else if (b == 2) {
    1633. k = 1;
    1634. }
    1635. else if (b == 32) {
    1636. k = 5;
    1637. }
    1638. else if (b == 4) {
    1639. k = 2;
    1640. }
    1641. else {
    1642. this.fromRadix(s, b);
    1643. return;
    1644. }
    1645. this.t = 0;
    1646. this.s = 0;
    1647. var i = s.length;
    1648. var mi = false;
    1649. var sh = 0;
    1650. while (--i >= 0) {
    1651. var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
    1652. if (x < 0) {
    1653. if (s.charAt(i) == "-") {
    1654. mi = true;
    1655. }
    1656. continue;
    1657. }
    1658. mi = false;
    1659. if (sh == 0) {
    1660. this[this.t++] = x;
    1661. }
    1662. else if (sh + k > this.DB) {
    1663. this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
    1664. this[this.t++] = (x >> (this.DB - sh));
    1665. }
    1666. else {
    1667. this[this.t - 1] |= x << sh;
    1668. }
    1669. sh += k;
    1670. if (sh >= this.DB) {
    1671. sh -= this.DB;
    1672. }
    1673. }
    1674. if (k == 8 && ((+s[0]) & 0x80) != 0) {
    1675. this.s = -1;
    1676. if (sh > 0) {
    1677. this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
    1678. }
    1679. }
    1680. this.clamp();
    1681. if (mi) {
    1682. BigInteger.ZERO.subTo(this, this);
    1683. }
    1684. };
    1685. // BigInteger.prototype.clamp = bnpClamp;
    1686. // (protected) clamp off excess high words
    1687. BigInteger.prototype.clamp = function () {
    1688. var c = this.s & this.DM;
    1689. while (this.t > 0 && this[this.t - 1] == c) {
    1690. --this.t;
    1691. }
    1692. };
    1693. // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
    1694. // (protected) r = this << n*DB
    1695. BigInteger.prototype.dlShiftTo = function (n, r) {
    1696. var i;
    1697. for (i = this.t - 1; i >= 0; --i) {
    1698. r[i + n] = this[i];
    1699. }
    1700. for (i = n - 1; i >= 0; --i) {
    1701. r[i] = 0;
    1702. }
    1703. r.t = this.t + n;
    1704. r.s = this.s;
    1705. };
    1706. // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
    1707. // (protected) r = this >> n*DB
    1708. BigInteger.prototype.drShiftTo = function (n, r) {
    1709. for (var i = n; i < this.t; ++i) {
    1710. r[i - n] = this[i];
    1711. }
    1712. r.t = Math.max(this.t - n, 0);
    1713. r.s = this.s;
    1714. };
    1715. // BigInteger.prototype.lShiftTo = bnpLShiftTo;
    1716. // (protected) r = this << n
    1717. BigInteger.prototype.lShiftTo = function (n, r) {
    1718. var bs = n % this.DB;
    1719. var cbs = this.DB - bs;
    1720. var bm = (1 << cbs) - 1;
    1721. var ds = Math.floor(n / this.DB);
    1722. var c = (this.s << bs) & this.DM;
    1723. for (var i = this.t - 1; i >= 0; --i) {
    1724. r[i + ds + 1] = (this[i] >> cbs) | c;
    1725. c = (this[i] & bm) << bs;
    1726. }
    1727. for (var i = ds - 1; i >= 0; --i) {
    1728. r[i] = 0;
    1729. }
    1730. r[ds] = c;
    1731. r.t = this.t + ds + 1;
    1732. r.s = this.s;
    1733. r.clamp();
    1734. };
    1735. // BigInteger.prototype.rShiftTo = bnpRShiftTo;
    1736. // (protected) r = this >> n
    1737. BigInteger.prototype.rShiftTo = function (n, r) {
    1738. r.s = this.s;
    1739. var ds = Math.floor(n / this.DB);
    1740. if (ds >= this.t) {
    1741. r.t = 0;
    1742. return;
    1743. }
    1744. var bs = n % this.DB;
    1745. var cbs = this.DB - bs;
    1746. var bm = (1 << bs) - 1;
    1747. r[0] = this[ds] >> bs;
    1748. for (var i = ds + 1; i < this.t; ++i) {
    1749. r[i - ds - 1] |= (this[i] & bm) << cbs;
    1750. r[i - ds] = this[i] >> bs;
    1751. }
    1752. if (bs > 0) {
    1753. r[this.t - ds - 1] |= (this.s & bm) << cbs;
    1754. }
    1755. r.t = this.t - ds;
    1756. r.clamp();
    1757. };
    1758. // BigInteger.prototype.subTo = bnpSubTo;
    1759. // (protected) r = this - a
    1760. BigInteger.prototype.subTo = function (a, r) {
    1761. var i = 0;
    1762. var c = 0;
    1763. var m = Math.min(a.t, this.t);
    1764. while (i < m) {
    1765. c += this[i] - a[i];
    1766. r[i++] = c & this.DM;
    1767. c >>= this.DB;
    1768. }
    1769. if (a.t < this.t) {
    1770. c -= a.s;
    1771. while (i < this.t) {
    1772. c += this[i];
    1773. r[i++] = c & this.DM;
    1774. c >>= this.DB;
    1775. }
    1776. c += this.s;
    1777. }
    1778. else {
    1779. c += this.s;
    1780. while (i < a.t) {
    1781. c -= a[i];
    1782. r[i++] = c & this.DM;
    1783. c >>= this.DB;
    1784. }
    1785. c -= a.s;
    1786. }
    1787. r.s = (c < 0) ? -1 : 0;
    1788. if (c < -1) {
    1789. r[i++] = this.DV + c;
    1790. }
    1791. else if (c > 0) {
    1792. r[i++] = c;
    1793. }
    1794. r.t = i;
    1795. r.clamp();
    1796. };
    1797. // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
    1798. // (protected) r = this * a, r != this,a (HAC 14.12)
    1799. // "this" should be the larger one if appropriate.
    1800. BigInteger.prototype.multiplyTo = function (a, r) {
    1801. var x = this.abs();
    1802. var y = a.abs();
    1803. var i = x.t;
    1804. r.t = i + y.t;
    1805. while (--i >= 0) {
    1806. r[i] = 0;
    1807. }
    1808. for (i = 0; i < y.t; ++i) {
    1809. r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
    1810. }
    1811. r.s = 0;
    1812. r.clamp();
    1813. if (this.s != a.s) {
    1814. BigInteger.ZERO.subTo(r, r);
    1815. }
    1816. };
    1817. // BigInteger.prototype.squareTo = bnpSquareTo;
    1818. // (protected) r = this^2, r != this (HAC 14.16)
    1819. BigInteger.prototype.squareTo = function (r) {
    1820. var x = this.abs();
    1821. var i = r.t = 2 * x.t;
    1822. while (--i >= 0) {
    1823. r[i] = 0;
    1824. }
    1825. for (i = 0; i < x.t - 1; ++i) {
    1826. var c = x.am(i, x[i], r, 2 * i, 0, 1);
    1827. if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
    1828. r[i + x.t] -= x.DV;
    1829. r[i + x.t + 1] = 1;
    1830. }
    1831. }
    1832. if (r.t > 0) {
    1833. r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
    1834. }
    1835. r.s = 0;
    1836. r.clamp();
    1837. };
    1838. // BigInteger.prototype.divRemTo = bnpDivRemTo;
    1839. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
    1840. // r != q, this != m. q or r may be null.
    1841. BigInteger.prototype.divRemTo = function (m, q, r) {
    1842. var pm = m.abs();
    1843. if (pm.t <= 0) {
    1844. return;
    1845. }
    1846. var pt = this.abs();
    1847. if (pt.t < pm.t) {
    1848. if (q != null) {
    1849. q.fromInt(0);
    1850. }
    1851. if (r != null) {
    1852. this.copyTo(r);
    1853. }
    1854. return;
    1855. }
    1856. if (r == null) {
    1857. r = nbi();
    1858. }
    1859. var y = nbi();
    1860. var ts = this.s;
    1861. var ms = m.s;
    1862. var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
    1863. if (nsh > 0) {
    1864. pm.lShiftTo(nsh, y);
    1865. pt.lShiftTo(nsh, r);
    1866. }
    1867. else {
    1868. pm.copyTo(y);
    1869. pt.copyTo(r);
    1870. }
    1871. var ys = y.t;
    1872. var y0 = y[ys - 1];
    1873. if (y0 == 0) {
    1874. return;
    1875. }
    1876. var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
    1877. var d1 = this.FV / yt;
    1878. var d2 = (1 << this.F1) / yt;
    1879. var e = 1 << this.F2;
    1880. var i = r.t;
    1881. var j = i - ys;
    1882. var t = (q == null) ? nbi() : q;
    1883. y.dlShiftTo(j, t);
    1884. if (r.compareTo(t) >= 0) {
    1885. r[r.t++] = 1;
    1886. r.subTo(t, r);
    1887. }
    1888. BigInteger.ONE.dlShiftTo(ys, t);
    1889. t.subTo(y, y); // "negative" y so we can replace sub with am later
    1890. while (y.t < ys) {
    1891. y[y.t++] = 0;
    1892. }
    1893. while (--j >= 0) {
    1894. // Estimate quotient digit
    1895. var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
    1896. if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
    1897. y.dlShiftTo(j, t);
    1898. r.subTo(t, r);
    1899. while (r[i] < --qd) {
    1900. r.subTo(t, r);
    1901. }
    1902. }
    1903. }
    1904. if (q != null) {
    1905. r.drShiftTo(ys, q);
    1906. if (ts != ms) {
    1907. BigInteger.ZERO.subTo(q, q);
    1908. }
    1909. }
    1910. r.t = ys;
    1911. r.clamp();
    1912. if (nsh > 0) {
    1913. r.rShiftTo(nsh, r);
    1914. } // Denormalize remainder
    1915. if (ts < 0) {
    1916. BigInteger.ZERO.subTo(r, r);
    1917. }
    1918. };
    1919. // BigInteger.prototype.invDigit = bnpInvDigit;
    1920. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
    1921. // justification:
    1922. // xy == 1 (mod m)
    1923. // xy = 1+km
    1924. // xy(2-xy) = (1+km)(1-km)
    1925. // x[y(2-xy)] = 1-k^2m^2
    1926. // x[y(2-xy)] == 1 (mod m^2)
    1927. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
    1928. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
    1929. // JS multiply "overflows" differently from C/C++, so care is needed here.
    1930. BigInteger.prototype.invDigit = function () {
    1931. if (this.t < 1) {
    1932. return 0;
    1933. }
    1934. var x = this[0];
    1935. if ((x & 1) == 0) {
    1936. return 0;
    1937. }
    1938. var y = x & 3; // y == 1/x mod 2^2
    1939. y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
    1940. y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
    1941. y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
    1942. // last step - calculate inverse mod DV directly;
    1943. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
    1944. y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
    1945. // we really want the negative inverse, and -DV < y < DV
    1946. return (y > 0) ? this.DV - y : -y;
    1947. };
    1948. // BigInteger.prototype.isEven = bnpIsEven;
    1949. // (protected) true iff this is even
    1950. BigInteger.prototype.isEven = function () {
    1951. return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
    1952. };
    1953. // BigInteger.prototype.exp = bnpExp;
    1954. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
    1955. BigInteger.prototype.exp = function (e, z) {
    1956. if (e > 0xffffffff || e < 1) {
    1957. return BigInteger.ONE;
    1958. }
    1959. var r = nbi();
    1960. var r2 = nbi();
    1961. var g = z.convert(this);
    1962. var i = nbits(e) - 1;
    1963. g.copyTo(r);
    1964. while (--i >= 0) {
    1965. z.sqrTo(r, r2);
    1966. if ((e & (1 << i)) > 0) {
    1967. z.mulTo(r2, g, r);
    1968. }
    1969. else {
    1970. var t = r;
    1971. r = r2;
    1972. r2 = t;
    1973. }
    1974. }
    1975. return z.revert(r);
    1976. };
    1977. // BigInteger.prototype.chunkSize = bnpChunkSize;
    1978. // (protected) return x s.t. r^x < DV
    1979. BigInteger.prototype.chunkSize = function (r) {
    1980. return Math.floor(Math.LN2 * this.DB / Math.log(r));
    1981. };
    1982. // BigInteger.prototype.toRadix = bnpToRadix;
    1983. // (protected) convert to radix string
    1984. BigInteger.prototype.toRadix = function (b) {
    1985. if (b == null) {
    1986. b = 10;
    1987. }
    1988. if (this.signum() == 0 || b < 2 || b > 36) {
    1989. return "0";
    1990. }
    1991. var cs = this.chunkSize(b);
    1992. var a = Math.pow(b, cs);
    1993. var d = nbv(a);
    1994. var y = nbi();
    1995. var z = nbi();
    1996. var r = "";
    1997. this.divRemTo(d, y, z);
    1998. while (y.signum() > 0) {
    1999. r = (a + z.intValue()).toString(b).substr(1) + r;
    2000. y.divRemTo(d, y, z);
    2001. }
    2002. return z.intValue().toString(b) + r;
    2003. };
    2004. // BigInteger.prototype.fromRadix = bnpFromRadix;
    2005. // (protected) convert from radix string
    2006. BigInteger.prototype.fromRadix = function (s, b) {
    2007. this.fromInt(0);
    2008. if (b == null) {
    2009. b = 10;
    2010. }
    2011. var cs = this.chunkSize(b);
    2012. var d = Math.pow(b, cs);
    2013. var mi = false;
    2014. var j = 0;
    2015. var w = 0;
    2016. for (var i = 0; i < s.length; ++i) {
    2017. var x = intAt(s, i);
    2018. if (x < 0) {
    2019. if (s.charAt(i) == "-" && this.signum() == 0) {
    2020. mi = true;
    2021. }
    2022. continue;
    2023. }
    2024. w = b * w + x;
    2025. if (++j >= cs) {
    2026. this.dMultiply(d);
    2027. this.dAddOffset(w, 0);
    2028. j = 0;
    2029. w = 0;
    2030. }
    2031. }
    2032. if (j > 0) {
    2033. this.dMultiply(Math.pow(b, j));
    2034. this.dAddOffset(w, 0);
    2035. }
    2036. if (mi) {
    2037. BigInteger.ZERO.subTo(this, this);
    2038. }
    2039. };
    2040. // BigInteger.prototype.fromNumber = bnpFromNumber;
    2041. // (protected) alternate constructor
    2042. BigInteger.prototype.fromNumber = function (a, b, c) {
    2043. if ("number" == typeof b) {
    2044. // new BigInteger(int,int,RNG)
    2045. if (a < 2) {
    2046. this.fromInt(1);
    2047. }
    2048. else {
    2049. this.fromNumber(a, c);
    2050. if (!this.testBit(a - 1)) {
    2051. // force MSB set
    2052. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
    2053. }
    2054. if (this.isEven()) {
    2055. this.dAddOffset(1, 0);
    2056. } // force odd
    2057. while (!this.isProbablePrime(b)) {
    2058. this.dAddOffset(2, 0);
    2059. if (this.bitLength() > a) {
    2060. this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
    2061. }
    2062. }
    2063. }
    2064. }
    2065. else {
    2066. // new BigInteger(int,RNG)
    2067. var x = [];
    2068. var t = a & 7;
    2069. x.length = (a >> 3) + 1;
    2070. b.nextBytes(x);
    2071. if (t > 0) {
    2072. x[0] &= ((1 << t) - 1);
    2073. }
    2074. else {
    2075. x[0] = 0;
    2076. }
    2077. this.fromString(x, 256);
    2078. }
    2079. };
    2080. // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
    2081. // (protected) r = this op a (bitwise)
    2082. BigInteger.prototype.bitwiseTo = function (a, op, r) {
    2083. var i;
    2084. var f;
    2085. var m = Math.min(a.t, this.t);
    2086. for (i = 0; i < m; ++i) {
    2087. r[i] = op(this[i], a[i]);
    2088. }
    2089. if (a.t < this.t) {
    2090. f = a.s & this.DM;
    2091. for (i = m; i < this.t; ++i) {
    2092. r[i] = op(this[i], f);
    2093. }
    2094. r.t = this.t;
    2095. }
    2096. else {
    2097. f = this.s & this.DM;
    2098. for (i = m; i < a.t; ++i) {
    2099. r[i] = op(f, a[i]);
    2100. }
    2101. r.t = a.t;
    2102. }
    2103. r.s = op(this.s, a.s);
    2104. r.clamp();
    2105. };
    2106. // BigInteger.prototype.changeBit = bnpChangeBit;
    2107. // (protected) this op (1<
    2108. BigInteger.prototype.changeBit = function (n, op) {
    2109. var r = BigInteger.ONE.shiftLeft(n);
    2110. this.bitwiseTo(r, op, r);
    2111. return r;
    2112. };
    2113. // BigInteger.prototype.addTo = bnpAddTo;
    2114. // (protected) r = this + a
    2115. BigInteger.prototype.addTo = function (a, r) {
    2116. var i = 0;
    2117. var c = 0;
    2118. var m = Math.min(a.t, this.t);
    2119. while (i < m) {
    2120. c += this[i] + a[i];
    2121. r[i++] = c & this.DM;
    2122. c >>= this.DB;
    2123. }
    2124. if (a.t < this.t) {
    2125. c += a.s;
    2126. while (i < this.t) {
    2127. c += this[i];
    2128. r[i++] = c & this.DM;
    2129. c >>= this.DB;
    2130. }
    2131. c += this.s;
    2132. }
    2133. else {
    2134. c += this.s;
    2135. while (i < a.t) {
    2136. c += a[i];
    2137. r[i++] = c & this.DM;
    2138. c >>= this.DB;
    2139. }
    2140. c += a.s;
    2141. }
    2142. r.s = (c < 0) ? -1 : 0;
    2143. if (c > 0) {
    2144. r[i++] = c;
    2145. }
    2146. else if (c < -1) {
    2147. r[i++] = this.DV + c;
    2148. }
    2149. r.t = i;
    2150. r.clamp();
    2151. };
    2152. // BigInteger.prototype.dMultiply = bnpDMultiply;
    2153. // (protected) this *= n, this >= 0, 1 < n < DV
    2154. BigInteger.prototype.dMultiply = function (n) {
    2155. this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
    2156. ++this.t;
    2157. this.clamp();
    2158. };
    2159. // BigInteger.prototype.dAddOffset = bnpDAddOffset;
    2160. // (protected) this += n << w words, this >= 0
    2161. BigInteger.prototype.dAddOffset = function (n, w) {
    2162. if (n == 0) {
    2163. return;
    2164. }
    2165. while (this.t <= w) {
    2166. this[this.t++] = 0;
    2167. }
    2168. this[w] += n;
    2169. while (this[w] >= this.DV) {
    2170. this[w] -= this.DV;
    2171. if (++w >= this.t) {
    2172. this[this.t++] = 0;
    2173. }
    2174. ++this[w];
    2175. }
    2176. };
    2177. // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
    2178. // (protected) r = lower n words of "this * a", a.t <= n
    2179. // "this" should be the larger one if appropriate.
    2180. BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
    2181. var i = Math.min(this.t + a.t, n);
    2182. r.s = 0; // assumes a,this >= 0
    2183. r.t = i;
    2184. while (i > 0) {
    2185. r[--i] = 0;
    2186. }
    2187. for (var j = r.t - this.t; i < j; ++i) {
    2188. r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
    2189. }
    2190. for (var j = Math.min(a.t, n); i < j; ++i) {
    2191. this.am(0, a[i], r, i, 0, n - i);
    2192. }
    2193. r.clamp();
    2194. };
    2195. // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
    2196. // (protected) r = "this * a" without lower n words, n > 0
    2197. // "this" should be the larger one if appropriate.
    2198. BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
    2199. --n;
    2200. var i = r.t = this.t + a.t - n;
    2201. r.s = 0; // assumes a,this >= 0
    2202. while (--i >= 0) {
    2203. r[i] = 0;
    2204. }
    2205. for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
    2206. r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
    2207. }
    2208. r.clamp();
    2209. r.drShiftTo(1, r);
    2210. };
    2211. // BigInteger.prototype.modInt = bnpModInt;
    2212. // (protected) this % n, n < 2^26
    2213. BigInteger.prototype.modInt = function (n) {
    2214. if (n <= 0) {
    2215. return 0;
    2216. }
    2217. var d = this.DV % n;
    2218. var r = (this.s < 0) ? n - 1 : 0;
    2219. if (this.t > 0) {
    2220. if (d == 0) {
    2221. r = this[0] % n;
    2222. }
    2223. else {
    2224. for (var i = this.t - 1; i >= 0; --i) {
    2225. r = (d * r + this[i]) % n;
    2226. }
    2227. }
    2228. }
    2229. return r;
    2230. };
    2231. // BigInteger.prototype.millerRabin = bnpMillerRabin;
    2232. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
    2233. BigInteger.prototype.millerRabin = function (t) {
    2234. var n1 = this.subtract(BigInteger.ONE);
    2235. var k = n1.getLowestSetBit();
    2236. if (k <= 0) {
    2237. return false;
    2238. }
    2239. var r = n1.shiftRight(k);
    2240. t = (t + 1) >> 1;
    2241. if (t > lowprimes.length) {
    2242. t = lowprimes.length;
    2243. }
    2244. var a = nbi();
    2245. for (var i = 0; i < t; ++i) {
    2246. // Pick bases at random, instead of starting at 2
    2247. a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
    2248. var y = a.modPow(r, this);
    2249. if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
    2250. var j = 1;
    2251. while (j++ < k && y.compareTo(n1) != 0) {
    2252. y = y.modPowInt(2, this);
    2253. if (y.compareTo(BigInteger.ONE) == 0) {
    2254. return false;
    2255. }
    2256. }
    2257. if (y.compareTo(n1) != 0) {
    2258. return false;
    2259. }
    2260. }
    2261. }
    2262. return true;
    2263. };
    2264. // BigInteger.prototype.square = bnSquare;
    2265. // (public) this^2
    2266. BigInteger.prototype.square = function () {
    2267. var r = nbi();
    2268. this.squareTo(r);
    2269. return r;
    2270. };
    2271. //#region ASYNC
    2272. // Public API method
    2273. BigInteger.prototype.gcda = function (a, callback) {
    2274. var x = (this.s < 0) ? this.negate() : this.clone();
    2275. var y = (a.s < 0) ? a.negate() : a.clone();
    2276. if (x.compareTo(y) < 0) {
    2277. var t = x;
    2278. x = y;
    2279. y = t;
    2280. }
    2281. var i = x.getLowestSetBit();
    2282. var g = y.getLowestSetBit();
    2283. if (g < 0) {
    2284. callback(x);
    2285. return;
    2286. }
    2287. if (i < g) {
    2288. g = i;
    2289. }
    2290. if (g > 0) {
    2291. x.rShiftTo(g, x);
    2292. y.rShiftTo(g, y);
    2293. }
    2294. // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
    2295. var gcda1 = function () {
    2296. if ((i = x.getLowestSetBit()) > 0) {
    2297. x.rShiftTo(i, x);
    2298. }
    2299. if ((i = y.getLowestSetBit()) > 0) {
    2300. y.rShiftTo(i, y);
    2301. }
    2302. if (x.compareTo(y) >= 0) {
    2303. x.subTo(y, x);
    2304. x.rShiftTo(1, x);
    2305. }
    2306. else {
    2307. y.subTo(x, y);
    2308. y.rShiftTo(1, y);
    2309. }
    2310. if (!(x.signum() > 0)) {
    2311. if (g > 0) {
    2312. y.lShiftTo(g, y);
    2313. }
    2314. setTimeout(function () { callback(y); }, 0); // escape
    2315. }
    2316. else {
    2317. setTimeout(gcda1, 0);
    2318. }
    2319. };
    2320. setTimeout(gcda1, 10);
    2321. };
    2322. // (protected) alternate constructor
    2323. BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
    2324. if ("number" == typeof b) {
    2325. if (a < 2) {
    2326. this.fromInt(1);
    2327. }
    2328. else {
    2329. this.fromNumber(a, c);
    2330. if (!this.testBit(a - 1)) {
    2331. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
    2332. }
    2333. if (this.isEven()) {
    2334. this.dAddOffset(1, 0);
    2335. }
    2336. var bnp_1 = this;
    2337. var bnpfn1_1 = function () {
    2338. bnp_1.dAddOffset(2, 0);
    2339. if (bnp_1.bitLength() > a) {
    2340. bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
    2341. }
    2342. if (bnp_1.isProbablePrime(b)) {
    2343. setTimeout(function () { callback(); }, 0); // escape
    2344. }
    2345. else {
    2346. setTimeout(bnpfn1_1, 0);
    2347. }
    2348. };
    2349. setTimeout(bnpfn1_1, 0);
    2350. }
    2351. }
    2352. else {
    2353. var x = [];
    2354. var t = a & 7;
    2355. x.length = (a >> 3) + 1;
    2356. b.nextBytes(x);
    2357. if (t > 0) {
    2358. x[0] &= ((1 << t) - 1);
    2359. }
    2360. else {
    2361. x[0] = 0;
    2362. }
    2363. this.fromString(x, 256);
    2364. }
    2365. };
    2366. return BigInteger;
    2367. }());
    2368. //#region REDUCERS
    2369. //#region NullExp
    2370. var NullExp = /** @class */ (function () {
    2371. function NullExp() {
    2372. }
    2373. // NullExp.prototype.convert = nNop;
    2374. NullExp.prototype.convert = function (x) {
    2375. return x;
    2376. };
    2377. // NullExp.prototype.revert = nNop;
    2378. NullExp.prototype.revert = function (x) {
    2379. return x;
    2380. };
    2381. // NullExp.prototype.mulTo = nMulTo;
    2382. NullExp.prototype.mulTo = function (x, y, r) {
    2383. x.multiplyTo(y, r);
    2384. };
    2385. // NullExp.prototype.sqrTo = nSqrTo;
    2386. NullExp.prototype.sqrTo = function (x, r) {
    2387. x.squareTo(r);
    2388. };
    2389. return NullExp;
    2390. }());
    2391. // Modular reduction using "classic" algorithm
    2392. var Classic = /** @class */ (function () {
    2393. function Classic(m) {
    2394. this.m = m;
    2395. }
    2396. // Classic.prototype.convert = cConvert;
    2397. Classic.prototype.convert = function (x) {
    2398. if (x.s < 0 || x.compareTo(this.m) >= 0) {
    2399. return x.mod(this.m);
    2400. }
    2401. else {
    2402. return x;
    2403. }
    2404. };
    2405. // Classic.prototype.revert = cRevert;
    2406. Classic.prototype.revert = function (x) {
    2407. return x;
    2408. };
    2409. // Classic.prototype.reduce = cReduce;
    2410. Classic.prototype.reduce = function (x) {
    2411. x.divRemTo(this.m, null, x);
    2412. };
    2413. // Classic.prototype.mulTo = cMulTo;
    2414. Classic.prototype.mulTo = function (x, y, r) {
    2415. x.multiplyTo(y, r);
    2416. this.reduce(r);
    2417. };
    2418. // Classic.prototype.sqrTo = cSqrTo;
    2419. Classic.prototype.sqrTo = function (x, r) {
    2420. x.squareTo(r);
    2421. this.reduce(r);
    2422. };
    2423. return Classic;
    2424. }());
    2425. //#endregion
    2426. //#region Montgomery
    2427. // Montgomery reduction
    2428. var Montgomery = /** @class */ (function () {
    2429. function Montgomery(m) {
    2430. this.m = m;
    2431. this.mp = m.invDigit();
    2432. this.mpl = this.mp & 0x7fff;
    2433. this.mph = this.mp >> 15;
    2434. this.um = (1 << (m.DB - 15)) - 1;
    2435. this.mt2 = 2 * m.t;
    2436. }
    2437. // Montgomery.prototype.convert = montConvert;
    2438. // xR mod m
    2439. Montgomery.prototype.convert = function (x) {
    2440. var r = nbi();
    2441. x.abs().dlShiftTo(this.m.t, r);
    2442. r.divRemTo(this.m, null, r);
    2443. if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
    2444. this.m.subTo(r, r);
    2445. }
    2446. return r;
    2447. };
    2448. // Montgomery.prototype.revert = montRevert;
    2449. // x/R mod m
    2450. Montgomery.prototype.revert = function (x) {
    2451. var r = nbi();
    2452. x.copyTo(r);
    2453. this.reduce(r);
    2454. return r;
    2455. };
    2456. // Montgomery.prototype.reduce = montReduce;
    2457. // x = x/R mod m (HAC 14.32)
    2458. Montgomery.prototype.reduce = function (x) {
    2459. while (x.t <= this.mt2) {
    2460. // pad x so am has enough room later
    2461. x[x.t++] = 0;
    2462. }
    2463. for (var i = 0; i < this.m.t; ++i) {
    2464. // faster way of calculating u0 = x[i]*mp mod DV
    2465. var j = x[i] & 0x7fff;
    2466. var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
    2467. // use am to combine the multiply-shift-add into one call
    2468. j = i + this.m.t;
    2469. x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
    2470. // propagate carry
    2471. while (x[j] >= x.DV) {
    2472. x[j] -= x.DV;
    2473. x[++j]++;
    2474. }
    2475. }
    2476. x.clamp();
    2477. x.drShiftTo(this.m.t, x);
    2478. if (x.compareTo(this.m) >= 0) {
    2479. x.subTo(this.m, x);
    2480. }
    2481. };
    2482. // Montgomery.prototype.mulTo = montMulTo;
    2483. // r = "xy/R mod m"; x,y != r
    2484. Montgomery.prototype.mulTo = function (x, y, r) {
    2485. x.multiplyTo(y, r);
    2486. this.reduce(r);
    2487. };
    2488. // Montgomery.prototype.sqrTo = montSqrTo;
    2489. // r = "x^2/R mod m"; x != r
    2490. Montgomery.prototype.sqrTo = function (x, r) {
    2491. x.squareTo(r);
    2492. this.reduce(r);
    2493. };
    2494. return Montgomery;
    2495. }());
    2496. //#endregion Montgomery
    2497. //#region Barrett
    2498. // Barrett modular reduction
    2499. var Barrett = /** @class */ (function () {
    2500. function Barrett(m) {
    2501. this.m = m;
    2502. // setup Barrett
    2503. this.r2 = nbi();
    2504. this.q3 = nbi();
    2505. BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
    2506. this.mu = this.r2.divide(m);
    2507. }
    2508. // Barrett.prototype.convert = barrettConvert;
    2509. Barrett.prototype.convert = function (x) {
    2510. if (x.s < 0 || x.t > 2 * this.m.t) {
    2511. return x.mod(this.m);
    2512. }
    2513. else if (x.compareTo(this.m) < 0) {
    2514. return x;
    2515. }
    2516. else {
    2517. var r = nbi();
    2518. x.copyTo(r);
    2519. this.reduce(r);
    2520. return r;
    2521. }
    2522. };
    2523. // Barrett.prototype.revert = barrettRevert;
    2524. Barrett.prototype.revert = function (x) {
    2525. return x;
    2526. };
    2527. // Barrett.prototype.reduce = barrettReduce;
    2528. // x = x mod m (HAC 14.42)
    2529. Barrett.prototype.reduce = function (x) {
    2530. x.drShiftTo(this.m.t - 1, this.r2);
    2531. if (x.t > this.m.t + 1) {
    2532. x.t = this.m.t + 1;
    2533. x.clamp();
    2534. }
    2535. this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
    2536. this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
    2537. while (x.compareTo(this.r2) < 0) {
    2538. x.dAddOffset(1, this.m.t + 1);
    2539. }
    2540. x.subTo(this.r2, x);
    2541. while (x.compareTo(this.m) >= 0) {
    2542. x.subTo(this.m, x);
    2543. }
    2544. };
    2545. // Barrett.prototype.mulTo = barrettMulTo;
    2546. // r = x*y mod m; x,y != r
    2547. Barrett.prototype.mulTo = function (x, y, r) {
    2548. x.multiplyTo(y, r);
    2549. this.reduce(r);
    2550. };
    2551. // Barrett.prototype.sqrTo = barrettSqrTo;
    2552. // r = x^2 mod m; x != r
    2553. Barrett.prototype.sqrTo = function (x, r) {
    2554. x.squareTo(r);
    2555. this.reduce(r);
    2556. };
    2557. return Barrett;
    2558. }());
    2559. //#endregion
    2560. //#endregion REDUCERS
    2561. // return new, unset BigInteger
    2562. function nbi() { return new BigInteger(null); }
    2563. function parseBigInt(str, r) {
    2564. return new BigInteger(str, r);
    2565. }
    2566. // am: Compute w_j += (x*this_i), propagate carries,
    2567. // c is initial carry, returns final carry.
    2568. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
    2569. // We need to select the fastest one that works in this environment.
    2570. // am1: use a single mult and divide to get the high bits,
    2571. // max digit bits should be 26 because
    2572. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
    2573. function am1(i, x, w, j, c, n) {
    2574. while (--n >= 0) {
    2575. var v = x * this[i++] + w[j] + c;
    2576. c = Math.floor(v / 0x4000000);
    2577. w[j++] = v & 0x3ffffff;
    2578. }
    2579. return c;
    2580. }
    2581. // am2 avoids a big mult-and-extract completely.
    2582. // Max digit bits should be <= 30 because we do bitwise ops
    2583. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
    2584. function am2(i, x, w, j, c, n) {
    2585. var xl = x & 0x7fff;
    2586. var xh = x >> 15;
    2587. while (--n >= 0) {
    2588. var l = this[i] & 0x7fff;
    2589. var h = this[i++] >> 15;
    2590. var m = xh * l + h * xl;
    2591. l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
    2592. c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
    2593. w[j++] = l & 0x3fffffff;
    2594. }
    2595. return c;
    2596. }
    2597. // Alternately, set max digit bits to 28 since some
    2598. // browsers slow down when dealing with 32-bit numbers.
    2599. function am3(i, x, w, j, c, n) {
    2600. var xl = x & 0x3fff;
    2601. var xh = x >> 14;
    2602. while (--n >= 0) {
    2603. var l = this[i] & 0x3fff;
    2604. var h = this[i++] >> 14;
    2605. var m = xh * l + h * xl;
    2606. l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
    2607. c = (l >> 28) + (m >> 14) + xh * h;
    2608. w[j++] = l & 0xfffffff;
    2609. }
    2610. return c;
    2611. }
    2612. if (j_lm && (navigator && navigator.appName == "Microsoft Internet Explorer")) {
    2613. BigInteger.prototype.am = am2;
    2614. dbits = 30;
    2615. }
    2616. else if (j_lm && (navigator && navigator.appName != "Netscape")) {
    2617. BigInteger.prototype.am = am1;
    2618. dbits = 26;
    2619. }
    2620. else { // Mozilla/Netscape seems to prefer am3
    2621. BigInteger.prototype.am = am3;
    2622. dbits = 28;
    2623. }
    2624. BigInteger.prototype.DB = dbits;
    2625. BigInteger.prototype.DM = ((1 << dbits) - 1);
    2626. BigInteger.prototype.DV = (1 << dbits);
    2627. var BI_FP = 52;
    2628. BigInteger.prototype.FV = Math.pow(2, BI_FP);
    2629. BigInteger.prototype.F1 = BI_FP - dbits;
    2630. BigInteger.prototype.F2 = 2 * dbits - BI_FP;
    2631. // Digit conversions
    2632. var BI_RC = [];
    2633. var rr;
    2634. var vv;
    2635. rr = "0".charCodeAt(0);
    2636. for (vv = 0; vv <= 9; ++vv) {
    2637. BI_RC[rr++] = vv;
    2638. }
    2639. rr = "a".charCodeAt(0);
    2640. for (vv = 10; vv < 36; ++vv) {
    2641. BI_RC[rr++] = vv;
    2642. }
    2643. rr = "A".charCodeAt(0);
    2644. for (vv = 10; vv < 36; ++vv) {
    2645. BI_RC[rr++] = vv;
    2646. }
    2647. function intAt(s, i) {
    2648. var c = BI_RC[s.charCodeAt(i)];
    2649. return (c == null) ? -1 : c;
    2650. }
    2651. // return bigint initialized to value
    2652. function nbv(i) {
    2653. var r = nbi();
    2654. r.fromInt(i);
    2655. return r;
    2656. }
    2657. // returns bit length of the integer x
    2658. function nbits(x) {
    2659. var r = 1;
    2660. var t;
    2661. if ((t = x >>> 16) != 0) {
    2662. x = t;
    2663. r += 16;
    2664. }
    2665. if ((t = x >> 8) != 0) {
    2666. x = t;
    2667. r += 8;
    2668. }
    2669. if ((t = x >> 4) != 0) {
    2670. x = t;
    2671. r += 4;
    2672. }
    2673. if ((t = x >> 2) != 0) {
    2674. x = t;
    2675. r += 2;
    2676. }
    2677. if ((t = x >> 1) != 0) {
    2678. x = t;
    2679. r += 1;
    2680. }
    2681. return r;
    2682. }
    2683. // "constants"
    2684. BigInteger.ZERO = nbv(0);
    2685. BigInteger.ONE = nbv(1);
    2686. // prng4.js - uses Arcfour as a PRNG
    2687. var Arcfour = /** @class */ (function () {
    2688. function Arcfour() {
    2689. this.i = 0;
    2690. this.j = 0;
    2691. this.S = [];
    2692. }
    2693. // Arcfour.prototype.init = ARC4init;
    2694. // Initialize arcfour context from key, an array of ints, each from [0..255]
    2695. Arcfour.prototype.init = function (key) {
    2696. var i;
    2697. var j;
    2698. var t;
    2699. for (i = 0; i < 256; ++i) {
    2700. this.S[i] = i;
    2701. }
    2702. j = 0;
    2703. for (i = 0; i < 256; ++i) {
    2704. j = (j + this.S[i] + key[i % key.length]) & 255;
    2705. t = this.S[i];
    2706. this.S[i] = this.S[j];
    2707. this.S[j] = t;
    2708. }
    2709. this.i = 0;
    2710. this.j = 0;
    2711. };
    2712. // Arcfour.prototype.next = ARC4next;
    2713. Arcfour.prototype.next = function () {
    2714. var t;
    2715. this.i = (this.i + 1) & 255;
    2716. this.j = (this.j + this.S[this.i]) & 255;
    2717. t = this.S[this.i];
    2718. this.S[this.i] = this.S[this.j];
    2719. this.S[this.j] = t;
    2720. return this.S[(t + this.S[this.i]) & 255];
    2721. };
    2722. return Arcfour;
    2723. }());
    2724. // Plug in your RNG constructor here
    2725. function prng_newstate() {
    2726. return new Arcfour();
    2727. }
    2728. // Pool size must be a multiple of 4 and greater than 32.
    2729. // An array of bytes the size of the pool will be passed to init()
    2730. var rng_psize = 256;
    2731. // Random number generator - requires a PRNG backend, e.g. prng4.js
    2732. var rng_state;
    2733. var rng_pool = null;
    2734. var rng_pptr;
    2735. // Initialize the pool with junk if needed.
    2736. if (rng_pool == null) {
    2737. rng_pool = [];
    2738. rng_pptr = 0;
    2739. var t = void 0;
    2740. if (window && window.crypto && window.crypto.getRandomValues) {
    2741. // Extract entropy (2048 bits) from RNG if available
    2742. var z = new Uint32Array(256);
    2743. window.crypto.getRandomValues(z);
    2744. for (t = 0; t < z.length; ++t) {
    2745. rng_pool[rng_pptr++] = z[t] & 255;
    2746. }
    2747. }
    2748. // Use mouse events for entropy, if we do not have enough entropy by the time
    2749. // we need it, entropy will be generated by Math.random.
    2750. var onMouseMoveListener_1 = function (ev) {
    2751. this.count = this.count || 0;
    2752. if (this.count >= 256 || rng_pptr >= rng_psize) {
    2753. if (window.removeEventListener) {
    2754. window.removeEventListener("mousemove", onMouseMoveListener_1, false);
    2755. }
    2756. else if (window.detachEvent) {
    2757. window.detachEvent("onmousemove", onMouseMoveListener_1);
    2758. }
    2759. return;
    2760. }
    2761. try {
    2762. var mouseCoordinates = ev.x + ev.y;
    2763. rng_pool[rng_pptr++] = mouseCoordinates & 255;
    2764. this.count += 1;
    2765. }
    2766. catch (e) {
    2767. // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
    2768. }
    2769. };
    2770. if (window && window.addEventListener) {
    2771. window.addEventListener("mousemove", onMouseMoveListener_1, false);
    2772. }
    2773. else if (window && window.attachEvent) {
    2774. window.attachEvent("onmousemove", onMouseMoveListener_1);
    2775. }
    2776. }
    2777. function rng_get_byte() {
    2778. if (rng_state == null) {
    2779. rng_state = prng_newstate();
    2780. // At this point, we may not have collected enough entropy. If not, fall back to Math.random
    2781. while (rng_pptr < rng_psize) {
    2782. var random = Math.floor(65536 * Math.random());
    2783. rng_pool[rng_pptr++] = random & 255;
    2784. }
    2785. rng_state.init(rng_pool);
    2786. for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
    2787. rng_pool[rng_pptr] = 0;
    2788. }
    2789. rng_pptr = 0;
    2790. }
    2791. // TODO: allow reseeding after first request
    2792. return rng_state.next();
    2793. }
    2794. var SecureRandom = /** @class */ (function () {
    2795. function SecureRandom() {
    2796. }
    2797. SecureRandom.prototype.nextBytes = function (ba) {
    2798. for (var i = 0; i < ba.length; ++i) {
    2799. ba[i] = rng_get_byte();
    2800. }
    2801. };
    2802. return SecureRandom;
    2803. }());
    2804. // Depends on jsbn.js and rng.js
    2805. // function linebrk(s,n) {
    2806. // var ret = "";
    2807. // var i = 0;
    2808. // while(i + n < s.length) {
    2809. // ret += s.substring(i,i+n) + "\n";
    2810. // i += n;
    2811. // }
    2812. // return ret + s.substring(i,s.length);
    2813. // }
    2814. // function byte2Hex(b) {
    2815. // if(b < 0x10)
    2816. // return "0" + b.toString(16);
    2817. // else
    2818. // return b.toString(16);
    2819. // }
    2820. function pkcs1pad1(s, n) {
    2821. if (n < s.length + 22) {
    2822. console.error("Message too long for RSA");
    2823. return null;
    2824. }
    2825. var len = n - s.length - 6;
    2826. var filler = "";
    2827. for (var f = 0; f < len; f += 2) {
    2828. filler += "ff";
    2829. }
    2830. var m = "0001" + filler + "00" + s;
    2831. return parseBigInt(m, 16);
    2832. }
    2833. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
    2834. function pkcs1pad2(s, n) {
    2835. if (n < s.length + 11) { // TODO: fix for utf-8
    2836. console.error("Message too long for RSA");
    2837. return null;
    2838. }
    2839. var ba = [];
    2840. var i = s.length - 1;
    2841. while (i >= 0 && n > 0) {
    2842. var c = s.charCodeAt(i--);
    2843. if (c < 128) { // encode using utf-8
    2844. ba[--n] = c;
    2845. }
    2846. else if ((c > 127) && (c < 2048)) {
    2847. ba[--n] = (c & 63) | 128;
    2848. ba[--n] = (c >> 6) | 192;
    2849. }
    2850. else {
    2851. ba[--n] = (c & 63) | 128;
    2852. ba[--n] = ((c >> 6) & 63) | 128;
    2853. ba[--n] = (c >> 12) | 224;
    2854. }
    2855. }
    2856. ba[--n] = 0;
    2857. var rng = new SecureRandom();
    2858. var x = [];
    2859. while (n > 2) { // random non-zero pad
    2860. x[0] = 0;
    2861. while (x[0] == 0) {
    2862. rng.nextBytes(x);
    2863. }
    2864. ba[--n] = x[0];
    2865. }
    2866. ba[--n] = 2;
    2867. ba[--n] = 0;
    2868. return new BigInteger(ba);
    2869. }
    2870. // "empty" RSA key constructor
    2871. var RSAKey = /** @class */ (function () {
    2872. function RSAKey() {
    2873. this.n = null;
    2874. this.e = 0;
    2875. this.d = null;
    2876. this.p = null;
    2877. this.q = null;
    2878. this.dmp1 = null;
    2879. this.dmq1 = null;
    2880. this.coeff = null;
    2881. }
    2882. //#region PROTECTED
    2883. // protected
    2884. // RSAKey.prototype.doPublic = RSADoPublic;
    2885. // Perform raw public operation on "x": return x^e (mod n)
    2886. RSAKey.prototype.doPublic = function (x) {
    2887. return x.modPowInt(this.e, this.n);
    2888. };
    2889. // RSAKey.prototype.doPrivate = RSADoPrivate;
    2890. // Perform raw private operation on "x": return x^d (mod n)
    2891. RSAKey.prototype.doPrivate = function (x) {
    2892. if (this.p == null || this.q == null) {
    2893. return x.modPow(this.d, this.n);
    2894. }
    2895. // TODO: re-calculate any missing CRT params
    2896. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
    2897. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
    2898. while (xp.compareTo(xq) < 0) {
    2899. xp = xp.add(this.p);
    2900. }
    2901. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
    2902. };
    2903. //#endregion PROTECTED
    2904. //#region PUBLIC
    2905. // RSAKey.prototype.setPublic = RSASetPublic;
    2906. // Set the public key fields N and e from hex strings
    2907. RSAKey.prototype.setPublic = function (N, E) {
    2908. if (N != null && E != null && N.length > 0 && E.length > 0) {
    2909. this.n = parseBigInt(N, 16);
    2910. this.e = parseInt(E, 16);
    2911. }
    2912. else {
    2913. console.error("Invalid RSA public key");
    2914. }
    2915. };
    2916. // RSAKey.prototype.encrypt = RSAEncrypt;
    2917. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
    2918. RSAKey.prototype.encrypt = function (text) {
    2919. var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
    2920. if (m == null) {
    2921. return null;
    2922. }
    2923. var c = this.doPublic(m);
    2924. if (c == null) {
    2925. return null;
    2926. }
    2927. var h = c.toString(16);
    2928. if ((h.length & 1) == 0) {
    2929. return h;
    2930. }
    2931. else {
    2932. return "0" + h;
    2933. }
    2934. };
    2935. // RSAKey.prototype.setPrivate = RSASetPrivate;
    2936. // Set the private key fields N, e, and d from hex strings
    2937. RSAKey.prototype.setPrivate = function (N, E, D) {
    2938. if (N != null && E != null && N.length > 0 && E.length > 0) {
    2939. this.n = parseBigInt(N, 16);
    2940. this.e = parseInt(E, 16);
    2941. this.d = parseBigInt(D, 16);
    2942. }
    2943. else {
    2944. console.error("Invalid RSA private key");
    2945. }
    2946. };
    2947. // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
    2948. // Set the private key fields N, e, d and CRT params from hex strings
    2949. RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
    2950. if (N != null && E != null && N.length > 0 && E.length > 0) {
    2951. this.n = parseBigInt(N, 16);
    2952. this.e = parseInt(E, 16);
    2953. this.d = parseBigInt(D, 16);
    2954. this.p = parseBigInt(P, 16);
    2955. this.q = parseBigInt(Q, 16);
    2956. this.dmp1 = parseBigInt(DP, 16);
    2957. this.dmq1 = parseBigInt(DQ, 16);
    2958. this.coeff = parseBigInt(C, 16);
    2959. }
    2960. else {
    2961. console.error("Invalid RSA private key");
    2962. }
    2963. };
    2964. // RSAKey.prototype.generate = RSAGenerate;
    2965. // Generate a new random private key B bits long, using public expt E
    2966. RSAKey.prototype.generate = function (B, E) {
    2967. var rng = new SecureRandom();
    2968. var qs = B >> 1;
    2969. this.e = parseInt(E, 16);
    2970. var ee = new BigInteger(E, 16);
    2971. for (;;) {
    2972. for (;;) {
    2973. this.p = new BigInteger(B - qs, 1, rng);
    2974. if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
    2975. break;
    2976. }
    2977. }
    2978. for (;;) {
    2979. this.q = new BigInteger(qs, 1, rng);
    2980. if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
    2981. break;
    2982. }
    2983. }
    2984. if (this.p.compareTo(this.q) <= 0) {
    2985. var t = this.p;
    2986. this.p = this.q;
    2987. this.q = t;
    2988. }
    2989. var p1 = this.p.subtract(BigInteger.ONE);
    2990. var q1 = this.q.subtract(BigInteger.ONE);
    2991. var phi = p1.multiply(q1);
    2992. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
    2993. this.n = this.p.multiply(this.q);
    2994. this.d = ee.modInverse(phi);
    2995. this.dmp1 = this.d.mod(p1);
    2996. this.dmq1 = this.d.mod(q1);
    2997. this.coeff = this.q.modInverse(this.p);
    2998. break;
    2999. }
    3000. }
    3001. };
    3002. // RSAKey.prototype.decrypt = RSADecrypt;
    3003. // Return the PKCS#1 RSA decryption of "ctext".
    3004. // "ctext" is an even-length hex string and the output is a plain string.
    3005. RSAKey.prototype.decrypt = function (ctext) {
    3006. var c = parseBigInt(ctext, 16);
    3007. var m = this.doPrivate(c);
    3008. if (m == null) {
    3009. return null;
    3010. }
    3011. return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
    3012. };
    3013. // Generate a new random private key B bits long, using public expt E
    3014. RSAKey.prototype.generateAsync = function (B, E, callback) {
    3015. var rng = new SecureRandom();
    3016. var qs = B >> 1;
    3017. this.e = parseInt(E, 16);
    3018. var ee = new BigInteger(E, 16);
    3019. var rsa = this;
    3020. // These functions have non-descript names because they were originally for(;;) loops.
    3021. // I don't know about cryptography to give them better names than loop1-4.
    3022. var loop1 = function () {
    3023. var loop4 = function () {
    3024. if (rsa.p.compareTo(rsa.q) <= 0) {
    3025. var t = rsa.p;
    3026. rsa.p = rsa.q;
    3027. rsa.q = t;
    3028. }
    3029. var p1 = rsa.p.subtract(BigInteger.ONE);
    3030. var q1 = rsa.q.subtract(BigInteger.ONE);
    3031. var phi = p1.multiply(q1);
    3032. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
    3033. rsa.n = rsa.p.multiply(rsa.q);
    3034. rsa.d = ee.modInverse(phi);
    3035. rsa.dmp1 = rsa.d.mod(p1);
    3036. rsa.dmq1 = rsa.d.mod(q1);
    3037. rsa.coeff = rsa.q.modInverse(rsa.p);
    3038. setTimeout(function () { callback(); }, 0); // escape
    3039. }
    3040. else {
    3041. setTimeout(loop1, 0);
    3042. }
    3043. };
    3044. var loop3 = function () {
    3045. rsa.q = nbi();
    3046. rsa.q.fromNumberAsync(qs, 1, rng, function () {
    3047. rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
    3048. if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
    3049. setTimeout(loop4, 0);
    3050. }
    3051. else {
    3052. setTimeout(loop3, 0);
    3053. }
    3054. });
    3055. });
    3056. };
    3057. var loop2 = function () {
    3058. rsa.p = nbi();
    3059. rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
    3060. rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
    3061. if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
    3062. setTimeout(loop3, 0);
    3063. }
    3064. else {
    3065. setTimeout(loop2, 0);
    3066. }
    3067. });
    3068. });
    3069. };
    3070. setTimeout(loop2, 0);
    3071. };
    3072. setTimeout(loop1, 0);
    3073. };
    3074. RSAKey.prototype.sign = function (text, digestMethod, digestName) {
    3075. var header = getDigestHeader(digestName);
    3076. var digest = header + digestMethod(text).toString();
    3077. var m = pkcs1pad1(digest, this.n.bitLength() / 4);
    3078. if (m == null) {
    3079. return null;
    3080. }
    3081. var c = this.doPrivate(m);
    3082. if (c == null) {
    3083. return null;
    3084. }
    3085. var h = c.toString(16);
    3086. if ((h.length & 1) == 0) {
    3087. return h;
    3088. }
    3089. else {
    3090. return "0" + h;
    3091. }
    3092. };
    3093. RSAKey.prototype.verify = function (text, signature, digestMethod) {
    3094. var c = parseBigInt(signature, 16);
    3095. var m = this.doPublic(c);
    3096. if (m == null) {
    3097. return null;
    3098. }
    3099. var unpadded = m.toString(16).replace(/^1f+00/, "");
    3100. var digest = removeDigestHeader(unpadded);
    3101. return digest == digestMethod(text).toString();
    3102. };
    3103. return RSAKey;
    3104. }());
    3105. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
    3106. function pkcs1unpad2(d, n) {
    3107. var b = d.toByteArray();
    3108. var i = 0;
    3109. while (i < b.length && b[i] == 0) {
    3110. ++i;
    3111. }
    3112. if (b.length - i != n - 1 || b[i] != 2) {
    3113. return null;
    3114. }
    3115. ++i;
    3116. while (b[i] != 0) {
    3117. if (++i >= b.length) {
    3118. return null;
    3119. }
    3120. }
    3121. var ret = "";
    3122. while (++i < b.length) {
    3123. var c = b[i] & 255;
    3124. if (c < 128) { // utf-8 decode
    3125. ret += String.fromCharCode(c);
    3126. }
    3127. else if ((c > 191) && (c < 224)) {
    3128. ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
    3129. ++i;
    3130. }
    3131. else {
    3132. ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
    3133. i += 2;
    3134. }
    3135. }
    3136. return ret;
    3137. }
    3138. // https://tools.ietf.org/html/rfc3447#page-43
    3139. var DIGEST_HEADERS = {
    3140. md2: "3020300c06082a864886f70d020205000410",
    3141. md5: "3020300c06082a864886f70d020505000410",
    3142. sha1: "3021300906052b0e03021a05000414",
    3143. sha224: "302d300d06096086480165030402040500041c",
    3144. sha256: "3031300d060960864801650304020105000420",
    3145. sha384: "3041300d060960864801650304020205000430",
    3146. sha512: "3051300d060960864801650304020305000440",
    3147. ripemd160: "3021300906052b2403020105000414",
    3148. };
    3149. function getDigestHeader(name) {
    3150. return DIGEST_HEADERS[name] || "";
    3151. }
    3152. function removeDigestHeader(str) {
    3153. for (var name_1 in DIGEST_HEADERS) {
    3154. if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
    3155. var header = DIGEST_HEADERS[name_1];
    3156. var len = header.length;
    3157. if (str.substr(0, len) == header) {
    3158. return str.substr(len);
    3159. }
    3160. }
    3161. }
    3162. return str;
    3163. }
    3164. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
    3165. // function RSAEncryptB64(text) {
    3166. // var h = this.encrypt(text);
    3167. // if(h) return hex2b64(h); else return null;
    3168. // }
    3169. // public
    3170. // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
    3171. /*!
    3172. Copyright (c) 2011, Yahoo! Inc. All rights reserved.
    3173. Code licensed under the BSD License:
    3174. http://developer.yahoo.com/yui/license.html
    3175. version: 2.9.0
    3176. */
    3177. var YAHOO = {};
    3178. YAHOO.lang = {
    3179. /**
    3180. * Utility to set up the prototype, constructor and superclass properties to
    3181. * support an inheritance strategy that can chain constructors and methods.
    3182. * Static members will not be inherited.
    3183. *
    3184. * @method extend
    3185. * @static
    3186. * @param {Function} subc the object to modify
    3187. * @param {Function} superc the object to inherit
    3188. * @param {Object} overrides additional properties/methods to add to the
    3189. * subclass prototype. These will override the
    3190. * matching items obtained from the superclass
    3191. * if present.
    3192. */
    3193. extend: function(subc, superc, overrides) {
    3194. if (! superc || ! subc) {
    3195. throw new Error("YAHOO.lang.extend failed, please check that " +
    3196. "all dependencies are included.");
    3197. }
    3198. var F = function() {};
    3199. F.prototype = superc.prototype;
    3200. subc.prototype = new F();
    3201. subc.prototype.constructor = subc;
    3202. subc.superclass = superc.prototype;
    3203. if (superc.prototype.constructor == Object.prototype.constructor) {
    3204. superc.prototype.constructor = superc;
    3205. }
    3206. if (overrides) {
    3207. var i;
    3208. for (i in overrides) {
    3209. subc.prototype[i] = overrides[i];
    3210. }
    3211. /*
    3212. * IE will not enumerate native functions in a derived object even if the
    3213. * function was overridden. This is a workaround for specific functions
    3214. * we care about on the Object prototype.
    3215. * @property _IEEnumFix
    3216. * @param {Function} r the object to receive the augmentation
    3217. * @param {Function} s the object that supplies the properties to augment
    3218. * @static
    3219. * @private
    3220. */
    3221. var _IEEnumFix = function() {},
    3222. ADD = ["toString", "valueOf"];
    3223. try {
    3224. if (/MSIE/.test(navigator.userAgent)) {
    3225. _IEEnumFix = function(r, s) {
    3226. for (i = 0; i < ADD.length; i = i + 1) {
    3227. var fname = ADD[i], f = s[fname];
    3228. if (typeof f === 'function' && f != Object.prototype[fname]) {
    3229. r[fname] = f;
    3230. }
    3231. }
    3232. };
    3233. }
    3234. } catch (ex) {} _IEEnumFix(subc.prototype, overrides);
    3235. }
    3236. }
    3237. };
    3238. /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
    3239. */
    3240. /**
    3241. * @fileOverview
    3242. * @name asn1-1.0.js
    3243. * @author Kenji Urushima kenji.urushima@gmail.com
    3244. * @version asn1 1.0.13 (2017-Jun-02)
    3245. * @since jsrsasign 2.1
    3246. * @license MIT License
    3247. */
    3248. /**
    3249. * kjur's class library name space
    3250. *

    3251. * This name space provides following name spaces:
    3252. *
      • *
      • {@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder
    3253. *
    3254. {@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL
  • *
  • {@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  • * class and utilities
  • *
  • *

  • * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  • * @name KJUR
  • * @namespace kjur's class library name space
  • */
  • var KJUR = {};
  • /**
  • * kjur's ASN.1 class library name space
  • *

  • * This is ITU-T X.690 ASN.1 DER encoder class library and
  • * class structure and methods is very similar to
  • * org.bouncycastle.asn1 package of
  • * well known BouncyCaslte Cryptography Library.
  • *

    PROVIDING ASN.1 PRIMITIVES

  • * Here are ASN.1 DER primitive classes.
  • *
    • *
    • 0x01 {@link KJUR.asn1.DERBoolean}
    • *
    • 0x02 {@link KJUR.asn1.DERInteger}
    • *
    • 0x03 {@link KJUR.asn1.DERBitString}
    • *
    • 0x04 {@link KJUR.asn1.DEROctetString}
    • *
    • 0x05 {@link KJUR.asn1.DERNull}
    • *
    • 0x06 {@link KJUR.asn1.DERObjectIdentifier}
    • *
    • 0x0a {@link KJUR.asn1.DEREnumerated}
    • *
    • 0x0c {@link KJUR.asn1.DERUTF8String}
    • *
    • 0x12 {@link KJUR.asn1.DERNumericString}
    • *
    • 0x13 {@link KJUR.asn1.DERPrintableString}
    • *
    • 0x14 {@link KJUR.asn1.DERTeletexString}
    • *
    • 0x16 {@link KJUR.asn1.DERIA5String}
    • *
    • 0x17 {@link KJUR.asn1.DERUTCTime}
    • *
    • 0x18 {@link KJUR.asn1.DERGeneralizedTime}
    • *
    • 0x30 {@link KJUR.asn1.DERSequence}
    • *
    • 0x31 {@link KJUR.asn1.DERSet}
    • *
    • *

      OTHER ASN.1 CLASSES

    • *
      • *
      • {@link KJUR.asn1.ASN1Object}
      • *
      • {@link KJUR.asn1.DERAbstractString}
      • *
      • {@link KJUR.asn1.DERAbstractTime}
      • *
      • {@link KJUR.asn1.DERAbstractStructured}
      • *
      • {@link KJUR.asn1.DERTaggedObject}
      • *
      • *

        SUB NAME SPACES

      • *
        • *
        • {@link KJUR.asn1.cades} - CAdES long term signature format
        • *
        • {@link KJUR.asn1.cms} - Cryptographic Message Syntax
        • *
        • {@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)
        • *
        • {@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format
        • *
        • {@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL
        • *
        • *

        • * NOTE: Please ignore method summary and document of this namespace.
        • * This caused by a bug of jsdoc2.
        • * @name KJUR.asn1
        • * @namespace
        • */
        • if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
        • /**
        • * ASN1 utilities class
        • * @name KJUR.asn1.ASN1Util
        • * @class ASN1 utilities class
        • * @since asn1 1.0.2
        • */
        • KJUR.asn1.ASN1Util = new function() {
        • this.integerToByteHex = function(i) {
        • var h = i.toString(16);
        • if ((h.length % 2) == 1) h = '0' + h;
        • return h;
        • };
        • this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
        • var h = bigIntegerValue.toString(16);
        • if (h.substr(0, 1) != '-') {
        • if (h.length % 2 == 1) {
        • h = '0' + h;
        • } else {
        • if (! h.match(/^[0-7]/)) {
        • h = '00' + h;
        • }
        • }
        • } else {
        • var hPos = h.substr(1);
        • var xorLen = hPos.length;
        • if (xorLen % 2 == 1) {
        • xorLen += 1;
        • } else {
        • if (! h.match(/^[0-7]/)) {
        • xorLen += 2;
        • }
        • }
        • var hMask = '';
        • for (var i = 0; i < xorLen; i++) {
        • hMask += 'f';
        • }
        • var biMask = new BigInteger(hMask, 16);
        • var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
        • h = biNeg.toString(16).replace(/^-/, '');
        • }
        • return h;
        • };
        • /**
        • * get PEM string from hexadecimal data and header string
        • * @name getPEMStringFromHex
        • * @memberOf KJUR.asn1.ASN1Util
        • * @function
        • * @param {String} dataHex hexadecimal string of PEM body
        • * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
        • * @return {String} PEM formatted string of input data
        • * @description
        • * This method converts a hexadecimal string to a PEM string with
        • * a specified header. Its line break will be CRLF("\r\n").
        • * @example
        • * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
        • * // value of pem will be:
        • * -----BEGIN PRIVATE KEY-----
        • * YWFh
        • * -----END PRIVATE KEY-----
        • */
        • this.getPEMStringFromHex = function(dataHex, pemHeader) {
        • return hextopem(dataHex, pemHeader);
        • };
        • /**
        • * generate ASN1Object specifed by JSON parameters
        • * @name newObject
        • * @memberOf KJUR.asn1.ASN1Util
        • * @function
        • * @param {Array} param JSON parameter to generate ASN1Object
        • * @return {KJUR.asn1.ASN1Object} generated object
        • * @since asn1 1.0.3
        • * @description
        • * generate any ASN1Object specified by JSON param
        • * including ASN.1 primitive or structured.
        • * Generally 'param' can be described as follows:
        • *
        • * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
        • *
        • * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
        • *
          • *
          • 'bool' - DERBoolean
          • *
          • 'int' - DERInteger
          • *
          • 'bitstr' - DERBitString
          • *
          • 'octstr' - DEROctetString
          • *
          • 'null' - DERNull
          • *
          • 'oid' - DERObjectIdentifier
          • *
          • 'enum' - DEREnumerated
          • *
          • 'utf8str' - DERUTF8String
          • *
          • 'numstr' - DERNumericString
          • *
          • 'prnstr' - DERPrintableString
          • *
          • 'telstr' - DERTeletexString
          • *
          • 'ia5str' - DERIA5String
          • *
          • 'utctime' - DERUTCTime
          • *
          • 'gentime' - DERGeneralizedTime
          • *
          • 'seq' - DERSequence
          • *
          • 'set' - DERSet
          • *
          • 'tag' - DERTaggedObject
          • *
          • * @example
          • * newObject({'prnstr': 'aaa'});
          • * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
          • * // ASN.1 Tagged Object
          • * newObject({'tag': {'tag': 'a1',
          • * 'explicit': true,
          • * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
          • * // more simple representation of ASN.1 Tagged Object
          • * newObject({'tag': ['a1',
          • * true,
          • * {'seq': [
          • * {'int': 3},
          • * {'prnstr': 'aaa'}]}
          • * ]});
          • */
          • this.newObject = function(param) {
          • var _KJUR = KJUR,
          • _KJUR_asn1 = _KJUR.asn1,
          • _DERBoolean = _KJUR_asn1.DERBoolean,
          • _DERInteger = _KJUR_asn1.DERInteger,
          • _DERBitString = _KJUR_asn1.DERBitString,
          • _DEROctetString = _KJUR_asn1.DEROctetString,
          • _DERNull = _KJUR_asn1.DERNull,
          • _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
          • _DEREnumerated = _KJUR_asn1.DEREnumerated,
          • _DERUTF8String = _KJUR_asn1.DERUTF8String,
          • _DERNumericString = _KJUR_asn1.DERNumericString,
          • _DERPrintableString = _KJUR_asn1.DERPrintableString,
          • _DERTeletexString = _KJUR_asn1.DERTeletexString,
          • _DERIA5String = _KJUR_asn1.DERIA5String,
          • _DERUTCTime = _KJUR_asn1.DERUTCTime,
          • _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
          • _DERSequence = _KJUR_asn1.DERSequence,
          • _DERSet = _KJUR_asn1.DERSet,
          • _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
          • _newObject = _KJUR_asn1.ASN1Util.newObject;
          • var keys = Object.keys(param);
          • if (keys.length != 1)
          • throw "key of param shall be only one.";
          • var key = keys[0];
          • if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
          • throw "undefined key: " + key;
          • if (key == "bool") return new _DERBoolean(param[key]);
          • if (key == "int") return new _DERInteger(param[key]);
          • if (key == "bitstr") return new _DERBitString(param[key]);
          • if (key == "octstr") return new _DEROctetString(param[key]);
          • if (key == "null") return new _DERNull(param[key]);
          • if (key == "oid") return new _DERObjectIdentifier(param[key]);
          • if (key == "enum") return new _DEREnumerated(param[key]);
          • if (key == "utf8str") return new _DERUTF8String(param[key]);
          • if (key == "numstr") return new _DERNumericString(param[key]);
          • if (key == "prnstr") return new _DERPrintableString(param[key]);
          • if (key == "telstr") return new _DERTeletexString(param[key]);
          • if (key == "ia5str") return new _DERIA5String(param[key]);
          • if (key == "utctime") return new _DERUTCTime(param[key]);
          • if (key == "gentime") return new _DERGeneralizedTime(param[key]);
          • if (key == "seq") {
          • var paramList = param[key];
          • var a = [];
          • for (var i = 0; i < paramList.length; i++) {
          • var asn1Obj = _newObject(paramList[i]);
          • a.push(asn1Obj);
          • }
          • return new _DERSequence({'array': a});
          • }
          • if (key == "set") {
          • var paramList = param[key];
          • var a = [];
          • for (var i = 0; i < paramList.length; i++) {
          • var asn1Obj = _newObject(paramList[i]);
          • a.push(asn1Obj);
          • }
          • return new _DERSet({'array': a});
          • }
          • if (key == "tag") {
          • var tagParam = param[key];
          • if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
          • tagParam.length == 3) {
          • var obj = _newObject(tagParam[2]);
          • return new _DERTaggedObject({tag: tagParam[0],
          • explicit: tagParam[1],
          • obj: obj});
          • } else {
          • var newParam = {};
          • if (tagParam.explicit !== undefined)
          • newParam.explicit = tagParam.explicit;
          • if (tagParam.tag !== undefined)
          • newParam.tag = tagParam.tag;
          • if (tagParam.obj === undefined)
          • throw "obj shall be specified for 'tag'.";
          • newParam.obj = _newObject(tagParam.obj);
          • return new _DERTaggedObject(newParam);
          • }
          • }
          • };
          • /**
          • * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
          • * @name jsonToASN1HEX
          • * @memberOf KJUR.asn1.ASN1Util
          • * @function
          • * @param {Array} param JSON parameter to generate ASN1Object
          • * @return hexadecimal string of ASN1Object
          • * @since asn1 1.0.4
          • * @description
          • * As for ASN.1 object representation of JSON object,
          • * please see {@link newObject}.
          • * @example
          • * jsonToASN1HEX({'prnstr': 'aaa'});
          • */
          • this.jsonToASN1HEX = function(param) {
          • var asn1Obj = this.newObject(param);
          • return asn1Obj.getEncodedHex();
          • };
          • };
          • /**
          • * get dot noted oid number string from hexadecimal value of OID
          • * @name oidHexToInt
          • * @memberOf KJUR.asn1.ASN1Util
          • * @function
          • * @param {String} hex hexadecimal value of object identifier
          • * @return {String} dot noted string of object identifier
          • * @since jsrsasign 4.8.3 asn1 1.0.7
          • * @description
          • * This static method converts from hexadecimal string representation of
          • * ASN.1 value of object identifier to oid number string.
          • * @example
          • * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6"
          • */
          • KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
          • var s = "";
          • var i01 = parseInt(hex.substr(0, 2), 16);
          • var i0 = Math.floor(i01 / 40);
          • var i1 = i01 % 40;
          • var s = i0 + "." + i1;
          • var binbuf = "";
          • for (var i = 2; i < hex.length; i += 2) {
          • var value = parseInt(hex.substr(i, 2), 16);
          • var bin = ("00000000" + value.toString(2)).slice(- 8);
          • binbuf = binbuf + bin.substr(1, 7);
          • if (bin.substr(0, 1) == "0") {
          • var bi = new BigInteger(binbuf, 2);
          • s = s + "." + bi.toString(10);
          • binbuf = "";
          • }
          • }
          • return s;
          • };
          • /**
          • * get hexadecimal value of object identifier from dot noted oid value
          • * @name oidIntToHex
          • * @memberOf KJUR.asn1.ASN1Util
          • * @function
          • * @param {String} oidString dot noted string of object identifier
          • * @return {String} hexadecimal value of object identifier
          • * @since jsrsasign 4.8.3 asn1 1.0.7
          • * @description
          • * This static method converts from object identifier value string.
          • * to hexadecimal string representation of it.
          • * @example
          • * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406"
          • */
          • KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
          • var itox = function(i) {
          • var h = i.toString(16);
          • if (h.length == 1) h = '0' + h;
          • return h;
          • };
          • var roidtox = function(roid) {
          • var h = '';
          • var bi = new BigInteger(roid, 10);
          • var b = bi.toString(2);
          • var padLen = 7 - b.length % 7;
          • if (padLen == 7) padLen = 0;
          • var bPad = '';
          • for (var i = 0; i < padLen; i++) bPad += '0';
          • b = bPad + b;
          • for (var i = 0; i < b.length - 1; i += 7) {
          • var b8 = b.substr(i, 7);
          • if (i != b.length - 7) b8 = '1' + b8;
          • h += itox(parseInt(b8, 2));
          • }
          • return h;
          • };
          • if (! oidString.match(/^[0-9.]+$/)) {
          • throw "malformed oid string: " + oidString;
          • }
          • var h = '';
          • var a = oidString.split('.');
          • var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
          • h += itox(i0);
          • a.splice(0, 2);
          • for (var i = 0; i < a.length; i++) {
          • h += roidtox(a[i]);
          • }
          • return h;
          • };
          • // ********************************************************************
          • // Abstract ASN.1 Classes
          • // ********************************************************************
          • // ********************************************************************
          • /**
          • * base class for ASN.1 DER encoder object
          • * @name KJUR.asn1.ASN1Object
          • * @class base class for ASN.1 DER encoder object
          • * @property {Boolean} isModified flag whether internal data was changed
          • * @property {String} hTLV hexadecimal string of ASN.1 TLV
          • * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
          • * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
          • * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
          • * @description
          • */
          • KJUR.asn1.ASN1Object = function() {
          • var hV = '';
          • /**
          • * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
          • * @name getLengthHexFromValue
          • * @memberOf KJUR.asn1.ASN1Object#
          • * @function
          • * @return {String} hexadecimal string of ASN.1 TLV length(L)
          • */
          • this.getLengthHexFromValue = function() {
          • if (typeof this.hV == "undefined" || this.hV == null) {
          • throw "this.hV is null or undefined.";
          • }
          • if (this.hV.length % 2 == 1) {
          • throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
          • }
          • var n = this.hV.length / 2;
          • var hN = n.toString(16);
          • if (hN.length % 2 == 1) {
          • hN = "0" + hN;
          • }
          • if (n < 128) {
          • return hN;
          • } else {
          • var hNlen = hN.length / 2;
          • if (hNlen > 15) {
          • throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
          • }
          • var head = 128 + hNlen;
          • return head.toString(16) + hN;
          • }
          • };
          • /**
          • * get hexadecimal string of ASN.1 TLV bytes
          • * @name getEncodedHex
          • * @memberOf KJUR.asn1.ASN1Object#
          • * @function
          • * @return {String} hexadecimal string of ASN.1 TLV
          • */
          • this.getEncodedHex = function() {
          • if (this.hTLV == null || this.isModified) {
          • this.hV = this.getFreshValueHex();
          • this.hL = this.getLengthHexFromValue();
          • this.hTLV = this.hT + this.hL + this.hV;
          • this.isModified = false;
          • //alert("first time: " + this.hTLV);
          • }
          • return this.hTLV;
          • };
          • /**
          • * get hexadecimal string of ASN.1 TLV value(V) bytes
          • * @name getValueHex
          • * @memberOf KJUR.asn1.ASN1Object#
          • * @function
          • * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
          • */
          • this.getValueHex = function() {
          • this.getEncodedHex();
          • return this.hV;
          • };
          • this.getFreshValueHex = function() {
          • return '';
          • };
          • };
          • // == BEGIN DERAbstractString ================================================
          • /**
          • * base class for ASN.1 DER string classes
          • * @name KJUR.asn1.DERAbstractString
          • * @class base class for ASN.1 DER string classes
          • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
          • * @property {String} s internal string of value
          • * @extends KJUR.asn1.ASN1Object
          • * @description
          • *
          • * As for argument 'params' for constructor, you can specify one of
          • * following properties:
          • *
            • *
            • str - specify initial ASN.1 value(V) by a string
            • *
            • hex - specify initial ASN.1 value(V) by a hexadecimal string
            • *
            • * NOTE: 'params' can be omitted.
            • */
            • KJUR.asn1.DERAbstractString = function(params) {
            • KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
            • /**
            • * get string value of this string object
            • * @name getString
            • * @memberOf KJUR.asn1.DERAbstractString#
            • * @function
            • * @return {String} string value of this string object
            • */
            • this.getString = function() {
            • return this.s;
            • };
            • /**
            • * set value by a string
            • * @name setString
            • * @memberOf KJUR.asn1.DERAbstractString#
            • * @function
            • * @param {String} newS value by a string to set
            • */
            • this.setString = function(newS) {
            • this.hTLV = null;
            • this.isModified = true;
            • this.s = newS;
            • this.hV = stohex(this.s);
            • };
            • /**
            • * set value by a hexadecimal string
            • * @name setStringHex
            • * @memberOf KJUR.asn1.DERAbstractString#
            • * @function
            • * @param {String} newHexString value by a hexadecimal string to set
            • */
            • this.setStringHex = function(newHexString) {
            • this.hTLV = null;
            • this.isModified = true;
            • this.s = null;
            • this.hV = newHexString;
            • };
            • this.getFreshValueHex = function() {
            • return this.hV;
            • };
            • if (typeof params != "undefined") {
            • if (typeof params == "string") {
            • this.setString(params);
            • } else if (typeof params['str'] != "undefined") {
            • this.setString(params['str']);
            • } else if (typeof params['hex'] != "undefined") {
            • this.setStringHex(params['hex']);
            • }
            • }
            • };
            • YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
            • // == END DERAbstractString ================================================
            • // == BEGIN DERAbstractTime ==================================================
            • /**
            • * base class for ASN.1 DER Generalized/UTCTime class
            • * @name KJUR.asn1.DERAbstractTime
            • * @class base class for ASN.1 DER Generalized/UTCTime class
            • * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
            • * @extends KJUR.asn1.ASN1Object
            • * @description
            • * @see KJUR.asn1.ASN1Object - superclass
            • */
            • KJUR.asn1.DERAbstractTime = function(params) {
            • KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
            • // --- PRIVATE METHODS --------------------
            • this.localDateToUTC = function(d) {
            • utc = d.getTime() + (d.getTimezoneOffset() * 60000);
            • var utcDate = new Date(utc);
            • return utcDate;
            • };
            • /*
            • * format date string by Data object
            • * @name formatDate
            • * @memberOf KJUR.asn1.AbstractTime;
            • * @param {Date} dateObject
            • * @param {string} type 'utc' or 'gen'
            • * @param {boolean} withMillis flag for with millisections or not
            • * @description
            • * 'withMillis' flag is supported from asn1 1.0.6.
            • */
            • this.formatDate = function(dateObject, type, withMillis) {
            • var pad = this.zeroPadding;
            • var d = this.localDateToUTC(dateObject);
            • var year = String(d.getFullYear());
            • if (type == 'utc') year = year.substr(2, 2);
            • var month = pad(String(d.getMonth() + 1), 2);
            • var day = pad(String(d.getDate()), 2);
            • var hour = pad(String(d.getHours()), 2);
            • var min = pad(String(d.getMinutes()), 2);
            • var sec = pad(String(d.getSeconds()), 2);
            • var s = year + month + day + hour + min + sec;
            • if (withMillis === true) {
            • var millis = d.getMilliseconds();
            • if (millis != 0) {
            • var sMillis = pad(String(millis), 3);
            • sMillis = sMillis.replace(/[0]+$/, "");
            • s = s + "." + sMillis;
            • }
            • }
            • return s + "Z";
            • };
            • this.zeroPadding = function(s, len) {
            • if (s.length >= len) return s;
            • return new Array(len - s.length + 1).join('0') + s;
            • };
            • // --- PUBLIC METHODS --------------------
            • /**
            • * get string value of this string object
            • * @name getString
            • * @memberOf KJUR.asn1.DERAbstractTime#
            • * @function
            • * @return {String} string value of this time object
            • */
            • this.getString = function() {
            • return this.s;
            • };
            • /**
            • * set value by a string
            • * @name setString
            • * @memberOf KJUR.asn1.DERAbstractTime#
            • * @function
            • * @param {String} newS value by a string to set such like "130430235959Z"
            • */
            • this.setString = function(newS) {
            • this.hTLV = null;
            • this.isModified = true;
            • this.s = newS;
            • this.hV = stohex(newS);
            • };
            • /**
            • * set value by a Date object
            • * @name setByDateValue
            • * @memberOf KJUR.asn1.DERAbstractTime#
            • * @function
            • * @param {Integer} year year of date (ex. 2013)
            • * @param {Integer} month month of date between 1 and 12 (ex. 12)
            • * @param {Integer} day day of month
            • * @param {Integer} hour hours of date
            • * @param {Integer} min minutes of date
            • * @param {Integer} sec seconds of date
            • */
            • this.setByDateValue = function(year, month, day, hour, min, sec) {
            • var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
            • this.setByDate(dateObject);
            • };
            • this.getFreshValueHex = function() {
            • return this.hV;
            • };
            • };
            • YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
            • // == END DERAbstractTime ==================================================
            • // == BEGIN DERAbstractStructured ============================================
            • /**
            • * base class for ASN.1 DER structured class
            • * @name KJUR.asn1.DERAbstractStructured
            • * @class base class for ASN.1 DER structured class
            • * @property {Array} asn1Array internal array of ASN1Object
            • * @extends KJUR.asn1.ASN1Object
            • * @description
            • * @see KJUR.asn1.ASN1Object - superclass
            • */
            • KJUR.asn1.DERAbstractStructured = function(params) {
            • KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
            • /**
            • * set value by array of ASN1Object
            • * @name setByASN1ObjectArray
            • * @memberOf KJUR.asn1.DERAbstractStructured#
            • * @function
            • * @param {array} asn1ObjectArray array of ASN1Object to set
            • */
            • this.setByASN1ObjectArray = function(asn1ObjectArray) {
            • this.hTLV = null;
            • this.isModified = true;
            • this.asn1Array = asn1ObjectArray;
            • };
            • /**
            • * append an ASN1Object to internal array
            • * @name appendASN1Object
            • * @memberOf KJUR.asn1.DERAbstractStructured#
            • * @function
            • * @param {ASN1Object} asn1Object to add
            • */
            • this.appendASN1Object = function(asn1Object) {
            • this.hTLV = null;
            • this.isModified = true;
            • this.asn1Array.push(asn1Object);
            • };
            • this.asn1Array = new Array();
            • if (typeof params != "undefined") {
            • if (typeof params['array'] != "undefined") {
            • this.asn1Array = params['array'];
            • }
            • }
            • };
            • YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
            • // ********************************************************************
            • // ASN.1 Object Classes
            • // ********************************************************************
            • // ********************************************************************
            • /**
            • * class for ASN.1 DER Boolean
            • * @name KJUR.asn1.DERBoolean
            • * @class class for ASN.1 DER Boolean
            • * @extends KJUR.asn1.ASN1Object
            • * @description
            • * @see KJUR.asn1.ASN1Object - superclass
            • */
            • KJUR.asn1.DERBoolean = function() {
            • KJUR.asn1.DERBoolean.superclass.constructor.call(this);
            • this.hT = "01";
            • this.hTLV = "0101ff";
            • };
            • YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
            • // ********************************************************************
            • /**
            • * class for ASN.1 DER Integer
            • * @name KJUR.asn1.DERInteger
            • * @class class for ASN.1 DER Integer
            • * @extends KJUR.asn1.ASN1Object
            • * @description
            • *
            • * As for argument 'params' for constructor, you can specify one of
            • * following properties:
            • *
              • *
              • int - specify initial ASN.1 value(V) by integer value
              • *
              • bigint - specify initial ASN.1 value(V) by BigInteger object
              • *
              • hex - specify initial ASN.1 value(V) by a hexadecimal string
              • *
              • * NOTE: 'params' can be omitted.
              • */
              • KJUR.asn1.DERInteger = function(params) {
              • KJUR.asn1.DERInteger.superclass.constructor.call(this);
              • this.hT = "02";
              • /**
              • * set value by Tom Wu's BigInteger object
              • * @name setByBigInteger
              • * @memberOf KJUR.asn1.DERInteger#
              • * @function
              • * @param {BigInteger} bigIntegerValue to set
              • */
              • this.setByBigInteger = function(bigIntegerValue) {
              • this.hTLV = null;
              • this.isModified = true;
              • this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
              • };
              • /**
              • * set value by integer value
              • * @name setByInteger
              • * @memberOf KJUR.asn1.DERInteger
              • * @function
              • * @param {Integer} integer value to set
              • */
              • this.setByInteger = function(intValue) {
              • var bi = new BigInteger(String(intValue), 10);
              • this.setByBigInteger(bi);
              • };
              • /**
              • * set value by integer value
              • * @name setValueHex
              • * @memberOf KJUR.asn1.DERInteger#
              • * @function
              • * @param {String} hexadecimal string of integer value
              • * @description
              • *
              • * NOTE: Value shall be represented by minimum octet length of
              • * two's complement representation.
              • * @example
              • * new KJUR.asn1.DERInteger(123);
              • * new KJUR.asn1.DERInteger({'int': 123});
              • * new KJUR.asn1.DERInteger({'hex': '1fad'});
              • */
              • this.setValueHex = function(newHexString) {
              • this.hV = newHexString;
              • };
              • this.getFreshValueHex = function() {
              • return this.hV;
              • };
              • if (typeof params != "undefined") {
              • if (typeof params['bigint'] != "undefined") {
              • this.setByBigInteger(params['bigint']);
              • } else if (typeof params['int'] != "undefined") {
              • this.setByInteger(params['int']);
              • } else if (typeof params == "number") {
              • this.setByInteger(params);
              • } else if (typeof params['hex'] != "undefined") {
              • this.setValueHex(params['hex']);
              • }
              • }
              • };
              • YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
              • // ********************************************************************
              • /**
              • * class for ASN.1 DER encoded BitString primitive
              • * @name KJUR.asn1.DERBitString
              • * @class class for ASN.1 DER encoded BitString primitive
              • * @extends KJUR.asn1.ASN1Object
              • * @description
              • *
              • * As for argument 'params' for constructor, you can specify one of
              • * following properties:
              • *
                • *
                • bin - specify binary string (ex. '10111')
                • *
                • array - specify array of boolean (ex. [true,false,true,true])
                • *
                • hex - specify hexadecimal string of ASN.1 value(V) including unused bits
                • *
                • obj - specify {@link KJUR.asn1.ASN1Util.newObject}
                • * argument for "BitString encapsulates" structure.
                • *
                • * NOTE1: 'params' can be omitted.
                • * NOTE2: 'obj' parameter have been supported since
                • * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
                • * @example
                • * // default constructor
                • * o = new KJUR.asn1.DERBitString();
                • * // initialize with binary string
                • * o = new KJUR.asn1.DERBitString({bin: "1011"});
                • * // initialize with boolean array
                • * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
                • * // initialize with hexadecimal string (04 is unused bits)
                • * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
                • * // initialize with ASN1Util.newObject argument for encapsulated
                • * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
                • * // above generates a ASN.1 data like this:
                • * // BIT STRING, encapsulates {
                • * // SEQUENCE {
                • * // INTEGER 3
                • * // PrintableString 'aaa'
                • * // }
                • * // }
                • */
                • KJUR.asn1.DERBitString = function(params) {
                • if (params !== undefined && typeof params.obj !== "undefined") {
                • var o = KJUR.asn1.ASN1Util.newObject(params.obj);
                • params.hex = "00" + o.getEncodedHex();
                • }
                • KJUR.asn1.DERBitString.superclass.constructor.call(this);
                • this.hT = "03";
                • /**
                • * set ASN.1 value(V) by a hexadecimal string including unused bits
                • * @name setHexValueIncludingUnusedBits
                • * @memberOf KJUR.asn1.DERBitString#
                • * @function
                • * @param {String} newHexStringIncludingUnusedBits
                • */
                • this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
                • this.hTLV = null;
                • this.isModified = true;
                • this.hV = newHexStringIncludingUnusedBits;
                • };
                • /**
                • * set ASN.1 value(V) by unused bit and hexadecimal string of value
                • * @name setUnusedBitsAndHexValue
                • * @memberOf KJUR.asn1.DERBitString#
                • * @function
                • * @param {Integer} unusedBits
                • * @param {String} hValue
                • */
                • this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
                • if (unusedBits < 0 || 7 < unusedBits) {
                • throw "unused bits shall be from 0 to 7: u = " + unusedBits;
                • }
                • var hUnusedBits = "0" + unusedBits;
                • this.hTLV = null;
                • this.isModified = true;
                • this.hV = hUnusedBits + hValue;
                • };
                • /**
                • * set ASN.1 DER BitString by binary string
                • * @name setByBinaryString
                • * @memberOf KJUR.asn1.DERBitString#
                • * @function
                • * @param {String} binaryString binary value string (i.e. '10111')
                • * @description
                • * Its unused bits will be calculated automatically by length of
                • * 'binaryValue'.
                • * NOTE: Trailing zeros '0' will be ignored.
                • * @example
                • * o = new KJUR.asn1.DERBitString();
                • * o.setByBooleanArray("01011");
                • */
                • this.setByBinaryString = function(binaryString) {
                • binaryString = binaryString.replace(/0+$/, '');
                • var unusedBits = 8 - binaryString.length % 8;
                • if (unusedBits == 8) unusedBits = 0;
                • for (var i = 0; i <= unusedBits; i++) {
                • binaryString += '0';
                • }
                • var h = '';
                • for (var i = 0; i < binaryString.length - 1; i += 8) {
                • var b = binaryString.substr(i, 8);
                • var x = parseInt(b, 2).toString(16);
                • if (x.length == 1) x = '0' + x;
                • h += x;
                • }
                • this.hTLV = null;
                • this.isModified = true;
                • this.hV = '0' + unusedBits + h;
                • };
                • /**
                • * set ASN.1 TLV value(V) by an array of boolean
                • * @name setByBooleanArray
                • * @memberOf KJUR.asn1.DERBitString#
                • * @function
                • * @param {array} booleanArray array of boolean (ex. [true, false, true])
                • * @description
                • * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
                • * @example
                • * o = new KJUR.asn1.DERBitString();
                • * o.setByBooleanArray([false, true, false, true, true]);
                • */
                • this.setByBooleanArray = function(booleanArray) {
                • var s = '';
                • for (var i = 0; i < booleanArray.length; i++) {
                • if (booleanArray[i] == true) {
                • s += '1';
                • } else {
                • s += '0';
                • }
                • }
                • this.setByBinaryString(s);
                • };
                • /**
                • * generate an array of falses with specified length
                • * @name newFalseArray
                • * @memberOf KJUR.asn1.DERBitString
                • * @function
                • * @param {Integer} nLength length of array to generate
                • * @return {array} array of boolean falses
                • * @description
                • * This static method may be useful to initialize boolean array.
                • * @example
                • * o = new KJUR.asn1.DERBitString();
                • * o.newFalseArray(3) → [false, false, false]
                • */
                • this.newFalseArray = function(nLength) {
                • var a = new Array(nLength);
                • for (var i = 0; i < nLength; i++) {
                • a[i] = false;
                • }
                • return a;
                • };
                • this.getFreshValueHex = function() {
                • return this.hV;
                • };
                • if (typeof params != "undefined") {
                • if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
                • this.setHexValueIncludingUnusedBits(params);
                • } else if (typeof params['hex'] != "undefined") {
                • this.setHexValueIncludingUnusedBits(params['hex']);
                • } else if (typeof params['bin'] != "undefined") {
                • this.setByBinaryString(params['bin']);
                • } else if (typeof params['array'] != "undefined") {
                • this.setByBooleanArray(params['array']);
                • }
                • }
                • };
                • YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
                • // ********************************************************************
                • /**
                • * class for ASN.1 DER OctetString
                • * @name KJUR.asn1.DEROctetString
                • * @class class for ASN.1 DER OctetString
                • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                • * @extends KJUR.asn1.DERAbstractString
                • * @description
                • * This class provides ASN.1 OctetString simple type.
                • * Supported "params" attributes are:
                • *
                  • *
                  • str - to set a string as a value
                  • *
                  • hex - to set a hexadecimal string as a value
                  • *
                  • obj - to set a encapsulated ASN.1 value by JSON object
                  • * which is defined in {@link KJUR.asn1.ASN1Util.newObject}
                  • *
                  • * NOTE: A parameter 'obj' have been supported
                  • * for "OCTET STRING, encapsulates" structure.
                  • * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
                  • * @see KJUR.asn1.DERAbstractString - superclass
                  • * @example
                  • * // default constructor
                  • * o = new KJUR.asn1.DEROctetString();
                  • * // initialize with string
                  • * o = new KJUR.asn1.DEROctetString({str: "aaa"});
                  • * // initialize with hexadecimal string
                  • * o = new KJUR.asn1.DEROctetString({hex: "616161"});
                  • * // initialize with ASN1Util.newObject argument
                  • * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
                  • * // above generates a ASN.1 data like this:
                  • * // OCTET STRING, encapsulates {
                  • * // SEQUENCE {
                  • * // INTEGER 3
                  • * // PrintableString 'aaa'
                  • * // }
                  • * // }
                  • */
                  • KJUR.asn1.DEROctetString = function(params) {
                  • if (params !== undefined && typeof params.obj !== "undefined") {
                  • var o = KJUR.asn1.ASN1Util.newObject(params.obj);
                  • params.hex = o.getEncodedHex();
                  • }
                  • KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
                  • this.hT = "04";
                  • };
                  • YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
                  • // ********************************************************************
                  • /**
                  • * class for ASN.1 DER Null
                  • * @name KJUR.asn1.DERNull
                  • * @class class for ASN.1 DER Null
                  • * @extends KJUR.asn1.ASN1Object
                  • * @description
                  • * @see KJUR.asn1.ASN1Object - superclass
                  • */
                  • KJUR.asn1.DERNull = function() {
                  • KJUR.asn1.DERNull.superclass.constructor.call(this);
                  • this.hT = "05";
                  • this.hTLV = "0500";
                  • };
                  • YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
                  • // ********************************************************************
                  • /**
                  • * class for ASN.1 DER ObjectIdentifier
                  • * @name KJUR.asn1.DERObjectIdentifier
                  • * @class class for ASN.1 DER ObjectIdentifier
                  • * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
                  • * @extends KJUR.asn1.ASN1Object
                  • * @description
                  • *
                  • * As for argument 'params' for constructor, you can specify one of
                  • * following properties:
                  • *
                    • *
                    • oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)
                    • *
                    • hex - specify initial ASN.1 value(V) by a hexadecimal string
                    • *
                    • * NOTE: 'params' can be omitted.
                    • */
                    • KJUR.asn1.DERObjectIdentifier = function(params) {
                    • var itox = function(i) {
                    • var h = i.toString(16);
                    • if (h.length == 1) h = '0' + h;
                    • return h;
                    • };
                    • var roidtox = function(roid) {
                    • var h = '';
                    • var bi = new BigInteger(roid, 10);
                    • var b = bi.toString(2);
                    • var padLen = 7 - b.length % 7;
                    • if (padLen == 7) padLen = 0;
                    • var bPad = '';
                    • for (var i = 0; i < padLen; i++) bPad += '0';
                    • b = bPad + b;
                    • for (var i = 0; i < b.length - 1; i += 7) {
                    • var b8 = b.substr(i, 7);
                    • if (i != b.length - 7) b8 = '1' + b8;
                    • h += itox(parseInt(b8, 2));
                    • }
                    • return h;
                    • };
                    • KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
                    • this.hT = "06";
                    • /**
                    • * set value by a hexadecimal string
                    • * @name setValueHex
                    • * @memberOf KJUR.asn1.DERObjectIdentifier#
                    • * @function
                    • * @param {String} newHexString hexadecimal value of OID bytes
                    • */
                    • this.setValueHex = function(newHexString) {
                    • this.hTLV = null;
                    • this.isModified = true;
                    • this.s = null;
                    • this.hV = newHexString;
                    • };
                    • /**
                    • * set value by a OID string
                    • * @name setValueOidString
                    • * @memberOf KJUR.asn1.DERObjectIdentifier#
                    • * @function
                    • * @param {String} oidString OID string (ex. 2.5.4.13)
                    • * @example
                    • * o = new KJUR.asn1.DERObjectIdentifier();
                    • * o.setValueOidString("2.5.4.13");
                    • */
                    • this.setValueOidString = function(oidString) {
                    • if (! oidString.match(/^[0-9.]+$/)) {
                    • throw "malformed oid string: " + oidString;
                    • }
                    • var h = '';
                    • var a = oidString.split('.');
                    • var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
                    • h += itox(i0);
                    • a.splice(0, 2);
                    • for (var i = 0; i < a.length; i++) {
                    • h += roidtox(a[i]);
                    • }
                    • this.hTLV = null;
                    • this.isModified = true;
                    • this.s = null;
                    • this.hV = h;
                    • };
                    • /**
                    • * set value by a OID name
                    • * @name setValueName
                    • * @memberOf KJUR.asn1.DERObjectIdentifier#
                    • * @function
                    • * @param {String} oidName OID name (ex. 'serverAuth')
                    • * @since 1.0.1
                    • * @description
                    • * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
                    • * Otherwise raise error.
                    • * @example
                    • * o = new KJUR.asn1.DERObjectIdentifier();
                    • * o.setValueName("serverAuth");
                    • */
                    • this.setValueName = function(oidName) {
                    • var oid = KJUR.asn1.x509.OID.name2oid(oidName);
                    • if (oid !== '') {
                    • this.setValueOidString(oid);
                    • } else {
                    • throw "DERObjectIdentifier oidName undefined: " + oidName;
                    • }
                    • };
                    • this.getFreshValueHex = function() {
                    • return this.hV;
                    • };
                    • if (params !== undefined) {
                    • if (typeof params === "string") {
                    • if (params.match(/^[0-2].[0-9.]+$/)) {
                    • this.setValueOidString(params);
                    • } else {
                    • this.setValueName(params);
                    • }
                    • } else if (params.oid !== undefined) {
                    • this.setValueOidString(params.oid);
                    • } else if (params.hex !== undefined) {
                    • this.setValueHex(params.hex);
                    • } else if (params.name !== undefined) {
                    • this.setValueName(params.name);
                    • }
                    • }
                    • };
                    • YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
                    • // ********************************************************************
                    • /**
                    • * class for ASN.1 DER Enumerated
                    • * @name KJUR.asn1.DEREnumerated
                    • * @class class for ASN.1 DER Enumerated
                    • * @extends KJUR.asn1.ASN1Object
                    • * @description
                    • *
                    • * As for argument 'params' for constructor, you can specify one of
                    • * following properties:
                    • *
                      • *
                      • int - specify initial ASN.1 value(V) by integer value
                      • *
                      • hex - specify initial ASN.1 value(V) by a hexadecimal string
                      • *
                      • * NOTE: 'params' can be omitted.
                      • * @example
                      • * new KJUR.asn1.DEREnumerated(123);
                      • * new KJUR.asn1.DEREnumerated({int: 123});
                      • * new KJUR.asn1.DEREnumerated({hex: '1fad'});
                      • */
                      • KJUR.asn1.DEREnumerated = function(params) {
                      • KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
                      • this.hT = "0a";
                      • /**
                      • * set value by Tom Wu's BigInteger object
                      • * @name setByBigInteger
                      • * @memberOf KJUR.asn1.DEREnumerated#
                      • * @function
                      • * @param {BigInteger} bigIntegerValue to set
                      • */
                      • this.setByBigInteger = function(bigIntegerValue) {
                      • this.hTLV = null;
                      • this.isModified = true;
                      • this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
                      • };
                      • /**
                      • * set value by integer value
                      • * @name setByInteger
                      • * @memberOf KJUR.asn1.DEREnumerated#
                      • * @function
                      • * @param {Integer} integer value to set
                      • */
                      • this.setByInteger = function(intValue) {
                      • var bi = new BigInteger(String(intValue), 10);
                      • this.setByBigInteger(bi);
                      • };
                      • /**
                      • * set value by integer value
                      • * @name setValueHex
                      • * @memberOf KJUR.asn1.DEREnumerated#
                      • * @function
                      • * @param {String} hexadecimal string of integer value
                      • * @description
                      • *
                      • * NOTE: Value shall be represented by minimum octet length of
                      • * two's complement representation.
                      • */
                      • this.setValueHex = function(newHexString) {
                      • this.hV = newHexString;
                      • };
                      • this.getFreshValueHex = function() {
                      • return this.hV;
                      • };
                      • if (typeof params != "undefined") {
                      • if (typeof params['int'] != "undefined") {
                      • this.setByInteger(params['int']);
                      • } else if (typeof params == "number") {
                      • this.setByInteger(params);
                      • } else if (typeof params['hex'] != "undefined") {
                      • this.setValueHex(params['hex']);
                      • }
                      • }
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER UTF8String
                      • * @name KJUR.asn1.DERUTF8String
                      • * @class class for ASN.1 DER UTF8String
                      • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                      • * @extends KJUR.asn1.DERAbstractString
                      • * @description
                      • * @see KJUR.asn1.DERAbstractString - superclass
                      • */
                      • KJUR.asn1.DERUTF8String = function(params) {
                      • KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
                      • this.hT = "0c";
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER NumericString
                      • * @name KJUR.asn1.DERNumericString
                      • * @class class for ASN.1 DER NumericString
                      • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                      • * @extends KJUR.asn1.DERAbstractString
                      • * @description
                      • * @see KJUR.asn1.DERAbstractString - superclass
                      • */
                      • KJUR.asn1.DERNumericString = function(params) {
                      • KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
                      • this.hT = "12";
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER PrintableString
                      • * @name KJUR.asn1.DERPrintableString
                      • * @class class for ASN.1 DER PrintableString
                      • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                      • * @extends KJUR.asn1.DERAbstractString
                      • * @description
                      • * @see KJUR.asn1.DERAbstractString - superclass
                      • */
                      • KJUR.asn1.DERPrintableString = function(params) {
                      • KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
                      • this.hT = "13";
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER TeletexString
                      • * @name KJUR.asn1.DERTeletexString
                      • * @class class for ASN.1 DER TeletexString
                      • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                      • * @extends KJUR.asn1.DERAbstractString
                      • * @description
                      • * @see KJUR.asn1.DERAbstractString - superclass
                      • */
                      • KJUR.asn1.DERTeletexString = function(params) {
                      • KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
                      • this.hT = "14";
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER IA5String
                      • * @name KJUR.asn1.DERIA5String
                      • * @class class for ASN.1 DER IA5String
                      • * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
                      • * @extends KJUR.asn1.DERAbstractString
                      • * @description
                      • * @see KJUR.asn1.DERAbstractString - superclass
                      • */
                      • KJUR.asn1.DERIA5String = function(params) {
                      • KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
                      • this.hT = "16";
                      • };
                      • YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
                      • // ********************************************************************
                      • /**
                      • * class for ASN.1 DER UTCTime
                      • * @name KJUR.asn1.DERUTCTime
                      • * @class class for ASN.1 DER UTCTime
                      • * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
                      • * @extends KJUR.asn1.DERAbstractTime
                      • * @description
                      • *
                      • * As for argument 'params' for constructor, you can specify one of
                      • * following properties:
                      • *
                        • *
                        • str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')
                        • *
                        • hex - specify initial ASN.1 value(V) by a hexadecimal string
                        • *
                        • date - specify Date object.
                        • *
                        • * NOTE: 'params' can be omitted.
                        • *

                          EXAMPLES

                        • * @example
                        • * d1 = new KJUR.asn1.DERUTCTime();
                        • * d1.setString('130430125959Z');
                        • *
                        • * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
                        • * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
                        • * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
                        • */
                        • KJUR.asn1.DERUTCTime = function(params) {
                        • KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
                        • this.hT = "17";
                        • /**
                        • * set value by a Date object
                        • * @name setByDate
                        • * @memberOf KJUR.asn1.DERUTCTime#
                        • * @function
                        • * @param {Date} dateObject Date object to set ASN.1 value(V)
                        • * @example
                        • * o = new KJUR.asn1.DERUTCTime();
                        • * o.setByDate(new Date("2016/12/31"));
                        • */
                        • this.setByDate = function(dateObject) {
                        • this.hTLV = null;
                        • this.isModified = true;
                        • this.date = dateObject;
                        • this.s = this.formatDate(this.date, 'utc');
                        • this.hV = stohex(this.s);
                        • };
                        • this.getFreshValueHex = function() {
                        • if (typeof this.date == "undefined" && typeof this.s == "undefined") {
                        • this.date = new Date();
                        • this.s = this.formatDate(this.date, 'utc');
                        • this.hV = stohex(this.s);
                        • }
                        • return this.hV;
                        • };
                        • if (params !== undefined) {
                        • if (params.str !== undefined) {
                        • this.setString(params.str);
                        • } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
                        • this.setString(params);
                        • } else if (params.hex !== undefined) {
                        • this.setStringHex(params.hex);
                        • } else if (params.date !== undefined) {
                        • this.setByDate(params.date);
                        • }
                        • }
                        • };
                        • YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
                        • // ********************************************************************
                        • /**
                        • * class for ASN.1 DER GeneralizedTime
                        • * @name KJUR.asn1.DERGeneralizedTime
                        • * @class class for ASN.1 DER GeneralizedTime
                        • * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
                        • * @property {Boolean} withMillis flag to show milliseconds or not
                        • * @extends KJUR.asn1.DERAbstractTime
                        • * @description
                        • *
                        • * As for argument 'params' for constructor, you can specify one of
                        • * following properties:
                        • *
                          • *
                          • str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')
                          • *
                          • hex - specify initial ASN.1 value(V) by a hexadecimal string
                          • *
                          • date - specify Date object.
                          • *
                          • millis - specify flag to show milliseconds (from 1.0.6)
                          • *
                          • * NOTE1: 'params' can be omitted.
                          • * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
                          • */
                          • KJUR.asn1.DERGeneralizedTime = function(params) {
                          • KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
                          • this.hT = "18";
                          • this.withMillis = false;
                          • /**
                          • * set value by a Date object
                          • * @name setByDate
                          • * @memberOf KJUR.asn1.DERGeneralizedTime#
                          • * @function
                          • * @param {Date} dateObject Date object to set ASN.1 value(V)
                          • * @example
                          • * When you specify UTC time, use 'Date.UTC' method like this:
                          • * o1 = new DERUTCTime();
                          • * o1.setByDate(date);
                          • *
                          • * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
                          • */
                          • this.setByDate = function(dateObject) {
                          • this.hTLV = null;
                          • this.isModified = true;
                          • this.date = dateObject;
                          • this.s = this.formatDate(this.date, 'gen', this.withMillis);
                          • this.hV = stohex(this.s);
                          • };
                          • this.getFreshValueHex = function() {
                          • if (this.date === undefined && this.s === undefined) {
                          • this.date = new Date();
                          • this.s = this.formatDate(this.date, 'gen', this.withMillis);
                          • this.hV = stohex(this.s);
                          • }
                          • return this.hV;
                          • };
                          • if (params !== undefined) {
                          • if (params.str !== undefined) {
                          • this.setString(params.str);
                          • } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
                          • this.setString(params);
                          • } else if (params.hex !== undefined) {
                          • this.setStringHex(params.hex);
                          • } else if (params.date !== undefined) {
                          • this.setByDate(params.date);
                          • }
                          • if (params.millis === true) {
                          • this.withMillis = true;
                          • }
                          • }
                          • };
                          • YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
                          • // ********************************************************************
                          • /**
                          • * class for ASN.1 DER Sequence
                          • * @name KJUR.asn1.DERSequence
                          • * @class class for ASN.1 DER Sequence
                          • * @extends KJUR.asn1.DERAbstractStructured
                          • * @description
                          • *
                          • * As for argument 'params' for constructor, you can specify one of
                          • * following properties:
                          • *
                            • *
                            • array - specify array of ASN1Object to set elements of content
                            • *
                            • * NOTE: 'params' can be omitted.
                            • */
                            • KJUR.asn1.DERSequence = function(params) {
                            • KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
                            • this.hT = "30";
                            • this.getFreshValueHex = function() {
                            • var h = '';
                            • for (var i = 0; i < this.asn1Array.length; i++) {
                            • var asn1Obj = this.asn1Array[i];
                            • h += asn1Obj.getEncodedHex();
                            • }
                            • this.hV = h;
                            • return this.hV;
                            • };
                            • };
                            • YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
                            • // ********************************************************************
                            • /**
                            • * class for ASN.1 DER Set
                            • * @name KJUR.asn1.DERSet
                            • * @class class for ASN.1 DER Set
                            • * @extends KJUR.asn1.DERAbstractStructured
                            • * @description
                            • *
                            • * As for argument 'params' for constructor, you can specify one of
                            • * following properties:
                            • *
                              • *
                              • array - specify array of ASN1Object to set elements of content
                              • *
                              • sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.
                              • *
                              • * NOTE1: 'params' can be omitted.
                              • * NOTE2: sortflag is supported since 1.0.5.
                              • */
                              • KJUR.asn1.DERSet = function(params) {
                              • KJUR.asn1.DERSet.superclass.constructor.call(this, params);
                              • this.hT = "31";
                              • this.sortFlag = true; // item shall be sorted only in ASN.1 DER
                              • this.getFreshValueHex = function() {
                              • var a = new Array();
                              • for (var i = 0; i < this.asn1Array.length; i++) {
                              • var asn1Obj = this.asn1Array[i];
                              • a.push(asn1Obj.getEncodedHex());
                              • }
                              • if (this.sortFlag == true) a.sort();
                              • this.hV = a.join('');
                              • return this.hV;
                              • };
                              • if (typeof params != "undefined") {
                              • if (typeof params.sortflag != "undefined" &&
                              • params.sortflag == false)
                              • this.sortFlag = false;
                              • }
                              • };
                              • YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
                              • // ********************************************************************
                              • /**
                              • * class for ASN.1 DER TaggedObject
                              • * @name KJUR.asn1.DERTaggedObject
                              • * @class class for ASN.1 DER TaggedObject
                              • * @extends KJUR.asn1.ASN1Object
                              • * @description
                              • *
                              • * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
                              • * For example, if you find '[1]' tag in a ASN.1 dump,
                              • * 'tagNoHex' will be 'a1'.
                              • *
                              • * As for optional argument 'params' for constructor, you can specify *ANY* of
                              • * following properties:
                              • *
                                • *
                                • explicit - specify true if this is explicit tag otherwise false
                                • * (default is 'true').
                                • *
                                • tag - specify tag (default is 'a0' which means [0])
                                • *
                                • obj - specify ASN1Object which is tagged
                                • *
                                • * @example
                                • * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
                                • * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
                                • * hex = d2.getEncodedHex();
                                • */
                                • KJUR.asn1.DERTaggedObject = function(params) {
                                • KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
                                • this.hT = "a0";
                                • this.hV = '';
                                • this.isExplicit = true;
                                • this.asn1Object = null;
                                • /**
                                • * set value by an ASN1Object
                                • * @name setString
                                • * @memberOf KJUR.asn1.DERTaggedObject#
                                • * @function
                                • * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
                                • * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
                                • * @param {ASN1Object} asn1Object ASN.1 to encapsulate
                                • */
                                • this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
                                • this.hT = tagNoHex;
                                • this.isExplicit = isExplicitFlag;
                                • this.asn1Object = asn1Object;
                                • if (this.isExplicit) {
                                • this.hV = this.asn1Object.getEncodedHex();
                                • this.hTLV = null;
                                • this.isModified = true;
                                • } else {
                                • this.hV = null;
                                • this.hTLV = asn1Object.getEncodedHex();
                                • this.hTLV = this.hTLV.replace(/^../, tagNoHex);
                                • this.isModified = false;
                                • }
                                • };
                                • this.getFreshValueHex = function() {
                                • return this.hV;
                                • };
                                • if (typeof params != "undefined") {
                                • if (typeof params['tag'] != "undefined") {
                                • this.hT = params['tag'];
                                • }
                                • if (typeof params['explicit'] != "undefined") {
                                • this.isExplicit = params['explicit'];
                                • }
                                • if (typeof params['obj'] != "undefined") {
                                • this.asn1Object = params['obj'];
                                • this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
                                • }
                                • }
                                • };
                                • YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
                                • /**
                                • * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
                                • * This object is just a decorator for parsing the key parameter
                                • * @param {string|Object} key - The key in string format, or an object containing
                                • * the parameters needed to build a RSAKey object.
                                • * @constructor
                                • */
                                • var JSEncryptRSAKey = /** @class */ (function (_super) {
                                • __extends(JSEncryptRSAKey, _super);
                                • function JSEncryptRSAKey(key) {
                                • var _this = _super.call(this) || this;
                                • // Call the super constructor.
                                • // RSAKey.call(this);
                                • // If a key key was provided.
                                • if (key) {
                                • // If this is a string...
                                • if (typeof key === "string") {
                                • _this.parseKey(key);
                                • }
                                • else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
                                • JSEncryptRSAKey.hasPublicKeyProperty(key)) {
                                • // Set the values for the key.
                                • _this.parsePropertiesFrom(key);
                                • }
                                • }
                                • return _this;
                                • }
                                • /**
                                • * Method to parse a pem encoded string containing both a public or private key.
                                • * The method will translate the pem encoded string in a der encoded string and
                                • * will parse private key and public key parameters. This method accepts public key
                                • * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
                                • *
                                • * @todo Check how many rsa formats use the same format of pkcs #1.
                                • *
                                • * The format is defined as:
                                • * PublicKeyInfo ::= SEQUENCE {
                                • * algorithm AlgorithmIdentifier,
                                • * PublicKey BIT STRING
                                • * }
                                • * Where AlgorithmIdentifier is:
                                • * AlgorithmIdentifier ::= SEQUENCE {
                                • * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
                                • * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
                                • * }
                                • * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
                                • * RSAPublicKey ::= SEQUENCE {
                                • * modulus INTEGER, -- n
                                • * publicExponent INTEGER -- e
                                • * }
                                • * it's possible to examine the structure of the keys obtained from openssl using
                                • * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
                                • * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
                                • * @private
                                • */
                                • JSEncryptRSAKey.prototype.parseKey = function (pem) {
                                • try {
                                • var modulus = 0;
                                • var public_exponent = 0;
                                • var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
                                • var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
                                • var asn1 = ASN1.decode(der);
                                • // Fixes a bug with OpenSSL 1.0+ private keys
                                • if (asn1.sub.length === 3) {
                                • asn1 = asn1.sub[2].sub[0];
                                • }
                                • if (asn1.sub.length === 9) {
                                • // Parse the private key.
                                • modulus = asn1.sub[1].getHexStringValue(); // bigint
                                • this.n = parseBigInt(modulus, 16);
                                • public_exponent = asn1.sub[2].getHexStringValue(); // int
                                • this.e = parseInt(public_exponent, 16);
                                • var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
                                • this.d = parseBigInt(private_exponent, 16);
                                • var prime1 = asn1.sub[4].getHexStringValue(); // bigint
                                • this.p = parseBigInt(prime1, 16);
                                • var prime2 = asn1.sub[5].getHexStringValue(); // bigint
                                • this.q = parseBigInt(prime2, 16);
                                • var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
                                • this.dmp1 = parseBigInt(exponent1, 16);
                                • var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
                                • this.dmq1 = parseBigInt(exponent2, 16);
                                • var coefficient = asn1.sub[8].getHexStringValue(); // bigint
                                • this.coeff = parseBigInt(coefficient, 16);
                                • }
                                • else if (asn1.sub.length === 2) {
                                • // Parse the public key.
                                • var bit_string = asn1.sub[1];
                                • var sequence = bit_string.sub[0];
                                • modulus = sequence.sub[0].getHexStringValue();
                                • this.n = parseBigInt(modulus, 16);
                                • public_exponent = sequence.sub[1].getHexStringValue();
                                • this.e = parseInt(public_exponent, 16);
                                • }
                                • else {
                                • return false;
                                • }
                                • return true;
                                • }
                                • catch (ex) {
                                • return false;
                                • }
                                • };
                                • /**
                                • * Translate rsa parameters in a hex encoded string representing the rsa key.
                                • *
                                • * The translation follow the ASN.1 notation :
                                • * RSAPrivateKey ::= SEQUENCE {
                                • * version Version,
                                • * modulus INTEGER, -- n
                                • * publicExponent INTEGER, -- e
                                • * privateExponent INTEGER, -- d
                                • * prime1 INTEGER, -- p
                                • * prime2 INTEGER, -- q
                                • * exponent1 INTEGER, -- d mod (p1)
                                • * exponent2 INTEGER, -- d mod (q-1)
                                • * coefficient INTEGER, -- (inverse of q) mod p
                                • * }
                                • * @returns {string} DER Encoded String representing the rsa private key
                                • * @private
                                • */
                                • JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
                                • var options = {
                                • array: [
                                • new KJUR.asn1.DERInteger({ int: 0 }),
                                • new KJUR.asn1.DERInteger({ bigint: this.n }),
                                • new KJUR.asn1.DERInteger({ int: this.e }),
                                • new KJUR.asn1.DERInteger({ bigint: this.d }),
                                • new KJUR.asn1.DERInteger({ bigint: this.p }),
                                • new KJUR.asn1.DERInteger({ bigint: this.q }),
                                • new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
                                • new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
                                • new KJUR.asn1.DERInteger({ bigint: this.coeff })
                                • ]
                                • };
                                • var seq = new KJUR.asn1.DERSequence(options);
                                • return seq.getEncodedHex();
                                • };
                                • /**
                                • * base64 (pem) encoded version of the DER encoded representation
                                • * @returns {string} pem encoded representation without header and footer
                                • * @public
                                • */
                                • JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
                                • return hex2b64(this.getPrivateBaseKey());
                                • };
                                • /**
                                • * Translate rsa parameters in a hex encoded string representing the rsa public key.
                                • * The representation follow the ASN.1 notation :
                                • * PublicKeyInfo ::= SEQUENCE {
                                • * algorithm AlgorithmIdentifier,
                                • * PublicKey BIT STRING
                                • * }
                                • * Where AlgorithmIdentifier is:
                                • * AlgorithmIdentifier ::= SEQUENCE {
                                • * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
                                • * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
                                • * }
                                • * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
                                • * RSAPublicKey ::= SEQUENCE {
                                • * modulus INTEGER, -- n
                                • * publicExponent INTEGER -- e
                                • * }
                                • * @returns {string} DER Encoded String representing the rsa public key
                                • * @private
                                • */
                                • JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
                                • var first_sequence = new KJUR.asn1.DERSequence({
                                • array: [
                                • new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
                                • new KJUR.asn1.DERNull()
                                • ]
                                • });
                                • var second_sequence = new KJUR.asn1.DERSequence({
                                • array: [
                                • new KJUR.asn1.DERInteger({ bigint: this.n }),
                                • new KJUR.asn1.DERInteger({ int: this.e })
                                • ]
                                • });
                                • var bit_string = new KJUR.asn1.DERBitString({
                                • hex: "00" + second_sequence.getEncodedHex()
                                • });
                                • var seq = new KJUR.asn1.DERSequence({
                                • array: [
                                • first_sequence,
                                • bit_string
                                • ]
                                • });
                                • return seq.getEncodedHex();
                                • };
                                • /**
                                • * base64 (pem) encoded version of the DER encoded representation
                                • * @returns {string} pem encoded representation without header and footer
                                • * @public
                                • */
                                • JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
                                • return hex2b64(this.getPublicBaseKey());
                                • };
                                • /**
                                • * wrap the string in block of width chars. The default value for rsa keys is 64
                                • * characters.
                                • * @param {string} str the pem encoded string without header and footer
                                • * @param {Number} [width=64] - the length the string has to be wrapped at
                                • * @returns {string}
                                • * @private
                                • */
                                • JSEncryptRSAKey.wordwrap = function (str, width) {
                                • width = width || 64;
                                • if (!str) {
                                • return str;
                                • }
                                • var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
                                • return str.match(RegExp(regex, "g")).join("\n");
                                • };
                                • /**
                                • * Retrieve the pem encoded private key
                                • * @returns {string} the pem encoded private key with header/footer
                                • * @public
                                • */
                                • JSEncryptRSAKey.prototype.getPrivateKey = function () {
                                • var key = "-----BEGIN RSA PRIVATE KEY-----\n";
                                • key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
                                • key += "-----END RSA PRIVATE KEY-----";
                                • return key;
                                • };
                                • /**
                                • * Retrieve the pem encoded public key
                                • * @returns {string} the pem encoded public key with header/footer
                                • * @public
                                • */
                                • JSEncryptRSAKey.prototype.getPublicKey = function () {
                                • var key = "-----BEGIN PUBLIC KEY-----\n";
                                • key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
                                • key += "-----END PUBLIC KEY-----";
                                • return key;
                                • };
                                • /**
                                • * Check if the object contains the necessary parameters to populate the rsa modulus
                                • * and public exponent parameters.
                                • * @param {Object} [obj={}] - An object that may contain the two public key
                                • * parameters
                                • * @returns {boolean} true if the object contains both the modulus and the public exponent
                                • * properties (n and e)
                                • * @todo check for types of n and e. N should be a parseable bigInt object, E should
                                • * be a parseable integer number
                                • * @private
                                • */
                                • JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
                                • obj = obj || {};
                                • return (obj.hasOwnProperty("n") &&
                                • obj.hasOwnProperty("e"));
                                • };
                                • /**
                                • * Check if the object contains ALL the parameters of an RSA key.
                                • * @param {Object} [obj={}] - An object that may contain nine rsa key
                                • * parameters
                                • * @returns {boolean} true if the object contains all the parameters needed
                                • * @todo check for types of the parameters all the parameters but the public exponent
                                • * should be parseable bigint objects, the public exponent should be a parseable integer number
                                • * @private
                                • */
                                • JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
                                • obj = obj || {};
                                • return (obj.hasOwnProperty("n") &&
                                • obj.hasOwnProperty("e") &&
                                • obj.hasOwnProperty("d") &&
                                • obj.hasOwnProperty("p") &&
                                • obj.hasOwnProperty("q") &&
                                • obj.hasOwnProperty("dmp1") &&
                                • obj.hasOwnProperty("dmq1") &&
                                • obj.hasOwnProperty("coeff"));
                                • };
                                • /**
                                • * Parse the properties of obj in the current rsa object. Obj should AT LEAST
                                • * include the modulus and public exponent (n, e) parameters.
                                • * @param {Object} obj - the object containing rsa parameters
                                • * @private
                                • */
                                • JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
                                • this.n = obj.n;
                                • this.e = obj.e;
                                • if (obj.hasOwnProperty("d")) {
                                • this.d = obj.d;
                                • this.p = obj.p;
                                • this.q = obj.q;
                                • this.dmp1 = obj.dmp1;
                                • this.dmq1 = obj.dmq1;
                                • this.coeff = obj.coeff;
                                • }
                                • };
                                • return JSEncryptRSAKey;
                                • }(RSAKey));
                                • /**
                                • *
                                • * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
                                • * possible parameters are:
                                • * - default_key_size {number} default: 1024 the key size in bit
                                • * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
                                • * - log {boolean} default: false whether log warn/error or not
                                • * @constructor
                                • */
                                • var JSEncrypt = /** @class */ (function () {
                                • function JSEncrypt(options) {
                                • options = options || {};
                                • this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
                                • this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
                                • this.log = options.log || false;
                                • // The private and public key.
                                • this.key = null;
                                • }
                                • /**
                                • * Method to set the rsa key parameter (one method is enough to set both the public
                                • * and the private key, since the private key contains the public key paramenters)
                                • * Log a warning if logs are enabled
                                • * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
                                • * @public
                                • */
                                • JSEncrypt.prototype.setKey = function (key) {
                                • if (this.log && this.key) {
                                • console.warn("A key was already set, overriding existing.");
                                • }
                                • this.key = new JSEncryptRSAKey(key);
                                • };
                                • /**
                                • * Proxy method for setKey, for api compatibility
                                • * @see setKey
                                • * @public
                                • */
                                • JSEncrypt.prototype.setPrivateKey = function (privkey) {
                                • // Create the key.
                                • this.setKey(privkey);
                                • };
                                • /**
                                • * Proxy method for setKey, for api compatibility
                                • * @see setKey
                                • * @public
                                • */
                                • JSEncrypt.prototype.setPublicKey = function (pubkey) {
                                • // Sets the public key.
                                • this.setKey(pubkey);
                                • };
                                • /**
                                • * Proxy method for RSAKey object's decrypt, decrypt the string using the private
                                • * components of the rsa key object. Note that if the object was not set will be created
                                • * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
                                • * @param {string} str base64 encoded crypted string to decrypt
                                • * @return {string} the decrypted string
                                • * @public
                                • */
                                • JSEncrypt.prototype.decrypt = function (str) {
                                • // Return the decrypted string.
                                • try {
                                • return this.getKey().decrypt(b64tohex(str));
                                • }
                                • catch (ex) {
                                • return false;
                                • }
                                • };
                                • /**
                                • * Proxy method for RSAKey object's encrypt, encrypt the string using the public
                                • * components of the rsa key object. Note that if the object was not set will be created
                                • * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
                                • * @param {string} str the string to encrypt
                                • * @return {string} the encrypted string encoded in base64
                                • * @public
                                • */
                                • JSEncrypt.prototype.encrypt = function (str) {
                                • // Return the encrypted string.
                                • try {
                                • return hex2b64(this.getKey().encrypt(str));
                                • }
                                • catch (ex) {
                                • return false;
                                • }
                                • };
                                • /**
                                • * Proxy method for RSAKey object's sign.
                                • * @param {string} str the string to sign
                                • * @param {function} digestMethod hash method
                                • * @param {string} digestName the name of the hash algorithm
                                • * @return {string} the signature encoded in base64
                                • * @public
                                • */
                                • JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
                                • // return the RSA signature of 'str' in 'hex' format.
                                • try {
                                • return hex2b64(this.getKey().sign(str, digestMethod, digestName));
                                • }
                                • catch (ex) {
                                • return false;
                                • }
                                • };
                                • /**
                                • * Proxy method for RSAKey object's verify.
                                • * @param {string} str the string to verify
                                • * @param {string} signature the signature encoded in base64 to compare the string to
                                • * @param {function} digestMethod hash method
                                • * @return {boolean} whether the data and signature match
                                • * @public
                                • */
                                • JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
                                • // Return the decrypted 'digest' of the signature.
                                • try {
                                • return this.getKey().verify(str, b64tohex(signature), digestMethod);
                                • }
                                • catch (ex) {
                                • return false;
                                • }
                                • };
                                • /**
                                • * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
                                • * will be created and returned
                                • * @param {callback} [cb] the callback to be called if we want the key to be generated
                                • * in an async fashion
                                • * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
                                • * @public
                                • */
                                • JSEncrypt.prototype.getKey = function (cb) {
                                • // Only create new if it does not exist.
                                • if (!this.key) {
                                • // Get a new private key.
                                • this.key = new JSEncryptRSAKey();
                                • if (cb && {}.toString.call(cb) === "[object Function]") {
                                • this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
                                • return;
                                • }
                                • // Generate the key.
                                • this.key.generate(this.default_key_size, this.default_public_exponent);
                                • }
                                • return this.key;
                                • };
                                • /**
                                • * Returns the pem encoded representation of the private key
                                • * If the key doesn't exists a new key will be created
                                • * @returns {string} pem encoded representation of the private key WITH header and footer
                                • * @public
                                • */
                                • JSEncrypt.prototype.getPrivateKey = function () {
                                • // Return the private representation of this key.
                                • return this.getKey().getPrivateKey();
                                • };
                                • /**
                                • * Returns the pem encoded representation of the private key
                                • * If the key doesn't exists a new key will be created
                                • * @returns {string} pem encoded representation of the private key WITHOUT header and footer
                                • * @public
                                • */
                                • JSEncrypt.prototype.getPrivateKeyB64 = function () {
                                • // Return the private representation of this key.
                                • return this.getKey().getPrivateBaseKeyB64();
                                • };
                                • /**
                                • * Returns the pem encoded representation of the public key
                                • * If the key doesn't exists a new key will be created
                                • * @returns {string} pem encoded representation of the public key WITH header and footer
                                • * @public
                                • */
                                • JSEncrypt.prototype.getPublicKey = function () {
                                • // Return the private representation of this key.
                                • return this.getKey().getPublicKey();
                                • };
                                • /**
                                • * Returns the pem encoded representation of the public key
                                • * If the key doesn't exists a new key will be created
                                • * @returns {string} pem encoded representation of the public key WITHOUT header and footer
                                • * @public
                                • */
                                • JSEncrypt.prototype.getPublicKeyB64 = function () {
                                • // Return the private representation of this key.
                                • return this.getKey().getPublicBaseKeyB64();
                                • };
                                • JSEncrypt.version = "3.0.0-rc.1";
                                • return JSEncrypt;
                                • }());
                                • if(window){
                                • window.JSEncrypt = JSEncrypt;
                                • }
                                • exports.JSEncrypt = JSEncrypt;
                                • exports.default = JSEncrypt;
                                • Object.defineProperty(exports, '__esModule', { value: true });
                                • })));
                                • 相关阅读:
                                  window 自启动程序并定时检测进程(SpringBoot 项目)
                                  面试的时候要注意的坑
                                  年轻人想搞钱,这没什么好遮掩的
                                  2022年最新的西安Java培训机构十大排名榜单
                                  【Netty】nio阻塞&非阻塞&Selector
                                  美食杰项目 -- 首页(一)
                                  11 【Express服务端渲染】
                                  Oracle OCP 19c认证考试1Z0-082题库最新解析 第二十七题
                                  WebAssembly照亮了 Web端软件的未来
                                  Mysql数据库基础:DML数据操作语言
                                • 原文地址:https://blog.csdn.net/zd1007129657/article/details/127774741