node-opcua-crypto 4.10.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +9 -4
  2. package/dist/{chunk-GNEWUC7X.mjs → chunk-AXAFLVME.mjs} +9 -15
  3. package/dist/chunk-AXAFLVME.mjs.map +1 -0
  4. package/dist/{chunk-46EEAYVO.mjs → chunk-LHUQUHQQ.mjs} +845 -829
  5. package/dist/chunk-LHUQUHQQ.mjs.map +1 -0
  6. package/dist/chunk-RQA4DO2Z.mjs +1 -0
  7. package/dist/index.d.mts +2 -3
  8. package/dist/index.d.ts +2 -3
  9. package/dist/index.js +658 -701
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +9 -56
  12. package/dist/source/index.d.mts +1 -5
  13. package/dist/source/index.d.ts +1 -5
  14. package/dist/source/index.js +622 -658
  15. package/dist/source/index.js.map +1 -1
  16. package/dist/source/index.mjs +9 -54
  17. package/dist/source/index_web.d.mts +224 -234
  18. package/dist/source/index_web.d.ts +224 -234
  19. package/dist/source/index_web.js +650 -657
  20. package/dist/source/index_web.js.map +1 -1
  21. package/dist/source/index_web.mjs +9 -51
  22. package/dist/source_nodejs/index.d.mts +1 -2
  23. package/dist/source_nodejs/index.d.ts +1 -2
  24. package/dist/source_nodejs/index.js +46 -50
  25. package/dist/source_nodejs/index.js.map +1 -1
  26. package/dist/source_nodejs/index.mjs +3 -5
  27. package/package.json +9 -4
  28. package/dist/chunk-46EEAYVO.mjs.map +0 -1
  29. package/dist/chunk-GNEWUC7X.mjs.map +0 -1
  30. package/dist/chunk-VI4S2NM5.mjs +0 -38
  31. package/dist/chunk-VI4S2NM5.mjs.map +0 -1
  32. package/dist/index_web.d.mts +0 -5
  33. package/dist/index_web.d.ts +0 -5
  34. package/dist/index_web.js +0 -6414
  35. package/dist/index_web.js.map +0 -1
  36. package/dist/index_web.mjs +0 -195
  37. package/index.mjs +0 -1
  38. package/index_web.ts +0 -1
  39. package/web.d.ts +0 -1
  40. package/web.mjs +0 -1
  41. /package/dist/{index_web.mjs.map → chunk-RQA4DO2Z.mjs.map} +0 -0
@@ -17,24 +17,6 @@ var getFilename = () => fileURLToPath(import.meta.url);
17
17
  var getDirname = () => path.dirname(getFilename());
18
18
  var __dirname = /* @__PURE__ */ getDirname();
19
19
 
20
- // source/common.ts
21
- import __crypto from "crypto";
22
- var KeyObjectOrig = __crypto.KeyObject;
23
- var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = __crypto;
24
- function isKeyObject(mayBeKeyObject) {
25
- if (KeyObjectOrig) {
26
- return mayBeKeyObject instanceof KeyObjectOrig;
27
- }
28
- return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
29
- }
30
- var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
31
- CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
32
- CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
33
- CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
34
- CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
35
- return CertificatePurpose2;
36
- })(CertificatePurpose || {});
37
-
38
20
  // source/asn1.ts
39
21
  import assert from "assert";
40
22
 
@@ -341,33 +323,33 @@ var oid_map = {
341
323
  };
342
324
 
343
325
  // source/asn1.ts
344
- var TagType = /* @__PURE__ */ ((TagType3) => {
345
- TagType3[TagType3["BOOLEAN"] = 1] = "BOOLEAN";
346
- TagType3[TagType3["INTEGER"] = 2] = "INTEGER";
347
- TagType3[TagType3["BIT_STRING"] = 3] = "BIT_STRING";
348
- TagType3[TagType3["OCTET_STRING"] = 4] = "OCTET_STRING";
349
- TagType3[TagType3["NULL"] = 5] = "NULL";
350
- TagType3[TagType3["OBJECT_IDENTIFIER"] = 6] = "OBJECT_IDENTIFIER";
351
- TagType3[TagType3["UTF8String"] = 12] = "UTF8String";
352
- TagType3[TagType3["NumericString"] = 18] = "NumericString";
353
- TagType3[TagType3["PrintableString"] = 19] = "PrintableString";
354
- TagType3[TagType3["TeletexString"] = 20] = "TeletexString";
355
- TagType3[TagType3["IA5String"] = 22] = "IA5String";
356
- TagType3[TagType3["UTCTime"] = 23] = "UTCTime";
357
- TagType3[TagType3["GeneralizedTime"] = 24] = "GeneralizedTime";
358
- TagType3[TagType3["GraphicString"] = 25] = "GraphicString";
359
- TagType3[TagType3["VisibleString"] = 26] = "VisibleString";
360
- TagType3[TagType3["GeneralString"] = 27] = "GeneralString";
361
- TagType3[TagType3["UniversalString"] = 28] = "UniversalString";
362
- TagType3[TagType3["BMPString"] = 30] = "BMPString";
363
- TagType3[TagType3["SEQUENCE"] = 48] = "SEQUENCE";
364
- TagType3[TagType3["SET"] = 49] = "SET";
365
- TagType3[TagType3["CONTEXT_SPECIFIC0"] = 160] = "CONTEXT_SPECIFIC0";
366
- TagType3[TagType3["CONTEXT_SPECIFIC1"] = 161] = "CONTEXT_SPECIFIC1";
367
- TagType3[TagType3["CONTEXT_SPECIFIC2"] = 162] = "CONTEXT_SPECIFIC2";
368
- TagType3[TagType3["CONTEXT_SPECIFIC3"] = 163] = "CONTEXT_SPECIFIC3";
369
- TagType3[TagType3["A4"] = 164] = "A4";
370
- return TagType3;
326
+ var TagType = /* @__PURE__ */ ((TagType2) => {
327
+ TagType2[TagType2["BOOLEAN"] = 1] = "BOOLEAN";
328
+ TagType2[TagType2["INTEGER"] = 2] = "INTEGER";
329
+ TagType2[TagType2["BIT_STRING"] = 3] = "BIT_STRING";
330
+ TagType2[TagType2["OCTET_STRING"] = 4] = "OCTET_STRING";
331
+ TagType2[TagType2["NULL"] = 5] = "NULL";
332
+ TagType2[TagType2["OBJECT_IDENTIFIER"] = 6] = "OBJECT_IDENTIFIER";
333
+ TagType2[TagType2["UTF8String"] = 12] = "UTF8String";
334
+ TagType2[TagType2["NumericString"] = 18] = "NumericString";
335
+ TagType2[TagType2["PrintableString"] = 19] = "PrintableString";
336
+ TagType2[TagType2["TeletexString"] = 20] = "TeletexString";
337
+ TagType2[TagType2["IA5String"] = 22] = "IA5String";
338
+ TagType2[TagType2["UTCTime"] = 23] = "UTCTime";
339
+ TagType2[TagType2["GeneralizedTime"] = 24] = "GeneralizedTime";
340
+ TagType2[TagType2["GraphicString"] = 25] = "GraphicString";
341
+ TagType2[TagType2["VisibleString"] = 26] = "VisibleString";
342
+ TagType2[TagType2["GeneralString"] = 27] = "GeneralString";
343
+ TagType2[TagType2["UniversalString"] = 28] = "UniversalString";
344
+ TagType2[TagType2["BMPString"] = 30] = "BMPString";
345
+ TagType2[TagType2["SEQUENCE"] = 48] = "SEQUENCE";
346
+ TagType2[TagType2["SET"] = 49] = "SET";
347
+ TagType2[TagType2["CONTEXT_SPECIFIC0"] = 160] = "CONTEXT_SPECIFIC0";
348
+ TagType2[TagType2["CONTEXT_SPECIFIC1"] = 161] = "CONTEXT_SPECIFIC1";
349
+ TagType2[TagType2["CONTEXT_SPECIFIC2"] = 162] = "CONTEXT_SPECIFIC2";
350
+ TagType2[TagType2["CONTEXT_SPECIFIC3"] = 163] = "CONTEXT_SPECIFIC3";
351
+ TagType2[TagType2["A4"] = 164] = "A4";
352
+ return TagType2;
371
353
  })(TagType || {});
372
354
  function readTag(buf, pos) {
373
355
  const start = pos;
@@ -388,7 +370,7 @@ function readTag(buf, pos) {
388
370
  }
389
371
  return { start, tag, position: pos, length };
390
372
  }
391
- function _readStruct(buf, blockInfo) {
373
+ function readStruct(buf, blockInfo) {
392
374
  const length = blockInfo.length;
393
375
  let cursor = blockInfo.position;
394
376
  const end = blockInfo.position + length;
@@ -413,9 +395,9 @@ function parseBitString(buffer, start, end, maxLength) {
413
395
  }
414
396
  return intro + s;
415
397
  }
416
- function _readBitString(buffer, block) {
398
+ function readBitString(buffer, block) {
417
399
  assert(block.tag === 3 /* BIT_STRING */);
418
- const data = _getBlock(buffer, block);
400
+ const data = getBlock(buffer, block);
419
401
  const ignore_bits = data.readUInt8(0);
420
402
  return {
421
403
  lengthInBits: data.length * 8 - ignore_bits,
@@ -431,7 +413,7 @@ function formatBuffer2DigitHexWithColum(buffer) {
431
413
  }
432
414
  return value.join(":").toUpperCase().replace(/^(00:)*/, "");
433
415
  }
434
- function _readOctetString(buffer, block) {
416
+ function readOctetString(buffer, block) {
435
417
  assert(block.tag === 4 /* OCTET_STRING */);
436
418
  const tag = readTag(buffer, block.position);
437
419
  assert(tag.tag === 4 /* OCTET_STRING */);
@@ -440,19 +422,19 @@ function _readOctetString(buffer, block) {
440
422
  const b = buffer.subarray(pos, pos + nbBytes);
441
423
  return b;
442
424
  }
443
- function _getBlock(buffer, block) {
425
+ function getBlock(buffer, block) {
444
426
  const start = block.position;
445
427
  const end = block.position + block.length;
446
428
  return buffer.subarray(start, end);
447
429
  }
448
- function _readIntegerAsByteString(buffer, block) {
449
- return _getBlock(buffer, block);
430
+ function readIntegerAsByteString(buffer, block) {
431
+ return getBlock(buffer, block);
450
432
  }
451
- function _readListOfInteger(buffer) {
433
+ function readListOfInteger(buffer) {
452
434
  const block = readTag(buffer, 0);
453
- const inner_blocks = _readStruct(buffer, block);
435
+ const inner_blocks = readStruct(buffer, block);
454
436
  return inner_blocks.map((innerBlock) => {
455
- return _readIntegerAsByteString(buffer, innerBlock);
437
+ return readIntegerAsByteString(buffer, innerBlock);
456
438
  });
457
439
  }
458
440
  function parseOID(buffer, start, end) {
@@ -475,7 +457,7 @@ function parseOID(buffer, start, end) {
475
457
  assert(bits === 0);
476
458
  return s;
477
459
  }
478
- function _readObjectIdentifier(buffer, block) {
460
+ function readObjectIdentifier(buffer, block) {
479
461
  assert(block.tag === 6 /* OBJECT_IDENTIFIER */);
480
462
  const b = buffer.subarray(block.position, block.position + block.length);
481
463
  const oid = parseOID(b, 0, block.length);
@@ -484,33 +466,33 @@ function _readObjectIdentifier(buffer, block) {
484
466
  name: oid_map[oid] ? oid_map[oid].d : oid
485
467
  };
486
468
  }
487
- function _readAlgorithmIdentifier(buffer, block) {
488
- const inner_blocks = _readStruct(buffer, block);
469
+ function readAlgorithmIdentifier(buffer, block) {
470
+ const inner_blocks = readStruct(buffer, block);
489
471
  return {
490
- identifier: _readObjectIdentifier(buffer, inner_blocks[0]).name
472
+ identifier: readObjectIdentifier(buffer, inner_blocks[0]).name
491
473
  };
492
474
  }
493
- function _readECCAlgorithmIdentifier(buffer, block) {
494
- const inner_blocks = _readStruct(buffer, block);
475
+ function readECCAlgorithmIdentifier(buffer, block) {
476
+ const inner_blocks = readStruct(buffer, block);
495
477
  return {
496
- identifier: _readObjectIdentifier(buffer, inner_blocks[1]).name
478
+ identifier: readObjectIdentifier(buffer, inner_blocks[1]).name
497
479
  // difference with RSA as algorithm is second element of nested block
498
480
  };
499
481
  }
500
- function _readSignatureValueBin(buffer, block) {
501
- return _readBitString(buffer, block).data;
482
+ function readSignatureValueBin(buffer, block) {
483
+ return readBitString(buffer, block).data;
502
484
  }
503
- function _readSignatureValue(buffer, block) {
504
- return _readSignatureValueBin(buffer, block).toString("hex");
485
+ function readSignatureValue(buffer, block) {
486
+ return readSignatureValueBin(buffer, block).toString("hex");
505
487
  }
506
- function _readLongIntegerValue(buffer, block) {
488
+ function readLongIntegerValue(buffer, block) {
507
489
  assert(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
508
490
  const pos = block.position;
509
491
  const nbBytes = block.length;
510
492
  const buf = buffer.subarray(pos, pos + nbBytes);
511
493
  return buf;
512
494
  }
513
- function _readIntegerValue(buffer, block) {
495
+ function readIntegerValue(buffer, block) {
514
496
  assert(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
515
497
  let pos = block.position;
516
498
  const nbBytes = block.length;
@@ -522,7 +504,7 @@ function _readIntegerValue(buffer, block) {
522
504
  }
523
505
  return value;
524
506
  }
525
- function _readBooleanValue(buffer, block) {
507
+ function readBooleanValue(buffer, block) {
526
508
  assert(block.tag === 1 /* BOOLEAN */, "expecting a BOOLEAN tag. got " + TagType[block.tag]);
527
509
  const pos = block.position;
528
510
  const nbBytes = block.length;
@@ -530,9 +512,9 @@ function _readBooleanValue(buffer, block) {
530
512
  const value = buffer.readUInt8(pos) ? true : false;
531
513
  return value;
532
514
  }
533
- function _readVersionValue(buffer, block) {
515
+ function readVersionValue(buffer, block) {
534
516
  block = readTag(buffer, block.position);
535
- return _readIntegerValue(buffer, block);
517
+ return readIntegerValue(buffer, block);
536
518
  }
537
519
  function convertGeneralizedTime(str) {
538
520
  const year = parseInt(str.substr(0, 4), 10);
@@ -544,7 +526,7 @@ function convertGeneralizedTime(str) {
544
526
  return new Date(Date.UTC(year, month, day, hours, mins, secs));
545
527
  }
546
528
  function _readBMPString(buffer, block) {
547
- const strBuff = _getBlock(buffer, block);
529
+ const strBuff = getBlock(buffer, block);
548
530
  let str = "";
549
531
  for (let i = 0; i < strBuff.length; i += 2) {
550
532
  const word = strBuff.readUInt16BE(i);
@@ -562,10 +544,10 @@ function convertUTCTime(str) {
562
544
  year += year >= 50 ? 1900 : 2e3;
563
545
  return new Date(Date.UTC(year, month, day, hours, mins, secs));
564
546
  }
565
- function _readValue(buffer, block) {
547
+ function readValue(buffer, block) {
566
548
  switch (block.tag) {
567
549
  case 1 /* BOOLEAN */:
568
- return _readBooleanValue(buffer, block);
550
+ return readBooleanValue(buffer, block);
569
551
  case 30 /* BMPString */:
570
552
  return _readBMPString(buffer, block);
571
553
  case 19 /* PrintableString */:
@@ -573,50 +555,29 @@ function _readValue(buffer, block) {
573
555
  case 12 /* UTF8String */:
574
556
  case 18 /* NumericString */:
575
557
  case 22 /* IA5String */:
576
- return _getBlock(buffer, block).toString("ascii");
558
+ return getBlock(buffer, block).toString("ascii");
577
559
  case 23 /* UTCTime */:
578
- return convertUTCTime(_getBlock(buffer, block).toString("ascii"));
560
+ return convertUTCTime(getBlock(buffer, block).toString("ascii"));
579
561
  case 24 /* GeneralizedTime */:
580
- return convertGeneralizedTime(_getBlock(buffer, block).toString("ascii"));
562
+ return convertGeneralizedTime(getBlock(buffer, block).toString("ascii"));
581
563
  default:
582
564
  throw new Error("Invalid tag 0x" + block.tag.toString(16));
583
565
  }
584
566
  }
585
- function compactDirectoryName(d) {
586
- return JSON.stringify(d);
587
- }
588
- function _readDirectoryName(buffer, block) {
589
- const set_blocks = _readStruct(buffer, block);
590
- const names = {};
591
- for (const set_block of set_blocks) {
592
- assert(set_block.tag === 49);
593
- const blocks = _readStruct(buffer, set_block);
594
- assert(blocks.length === 1);
595
- assert(blocks[0].tag === 48);
596
- const sequenceBlock = _readStruct(buffer, blocks[0]);
597
- assert(sequenceBlock.length === 2);
598
- const type = _readObjectIdentifier(buffer, sequenceBlock[0]);
599
- names[type.name] = _readValue(buffer, sequenceBlock[1]);
600
- }
601
- return names;
602
- }
603
- function _findBlockAtIndex(blocks, index) {
567
+ function findBlockAtIndex(blocks, index) {
604
568
  const tmp = blocks.filter((b) => b.tag === 160 + index || b.tag === 128 + index);
605
569
  if (tmp.length === 0) {
606
570
  return null;
607
571
  }
608
572
  return tmp[0];
609
573
  }
610
- function _readTime(buffer, block) {
611
- return _readValue(buffer, block);
574
+ function readTime(buffer, block) {
575
+ return readValue(buffer, block);
612
576
  }
613
577
 
614
- // source/crypto_explore_certificate.ts
615
- import assert3 from "assert";
616
-
617
578
  // source/crypto_utils.ts
618
579
  import constants from "constants";
619
- import assert2 from "assert";
580
+ import assert4 from "assert";
620
581
  import {
621
582
  createHash,
622
583
  createSign,
@@ -631,197 +592,35 @@ var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (s
631
592
  return new Buffer(size);
632
593
  };
633
594
 
634
- // source/crypto_utils.ts
635
- import jsrsasign from "jsrsasign";
636
- var { hexy } = pkg_hexy;
637
- var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
638
- var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
639
- function identifyPemType(rawKey) {
640
- if (rawKey instanceof Buffer) {
641
- rawKey = rawKey.toString("utf8");
642
- }
643
- const match = PEM_TYPE_REGEX.exec(rawKey);
644
- return !match ? void 0 : match[2];
645
- }
646
- function removeTrailingLF(str) {
647
- const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
648
- return tmp;
649
- }
650
- function toPem(raw_key, pem) {
651
- assert2(raw_key, "expecting a key");
652
- assert2(typeof pem === "string");
653
- let pemType = identifyPemType(raw_key);
654
- if (pemType) {
655
- return raw_key instanceof Buffer ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
656
- } else {
657
- pemType = pem;
658
- assert2(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
659
- let b = raw_key.toString("base64");
660
- let str = "-----BEGIN " + pemType + "-----\n";
661
- while (b.length) {
662
- str += b.substring(0, 64) + "\n";
663
- b = b.substring(64);
664
- }
665
- str += "-----END " + pemType + "-----";
666
- return str;
667
- }
668
- }
669
- function convertPEMtoDER(raw_key) {
670
- let match;
671
- let pemType;
672
- let base64str;
673
- const parts = [];
674
- PEM_REGEX.lastIndex = 0;
675
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
676
- pemType = match[2];
677
- base64str = match[3];
678
- base64str = base64str.replace(/\r?\n/g, "");
679
- parts.push(Buffer.from(base64str, "base64"));
680
- }
681
- return combine_der(parts);
682
- }
683
- function hexDump(buffer, width) {
684
- if (!buffer) {
685
- return "<>";
686
- }
687
- width = width || 32;
688
- if (buffer.length > 1024) {
689
- return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
690
- } else {
691
- return hexy(buffer, { width, format: "twos" });
692
- }
693
- }
694
- function makeMessageChunkSignature(chunk, options) {
695
- const signer = createSign(options.algorithm);
696
- signer.update(chunk);
697
- const signature = signer.sign(options.privateKey.hidden);
698
- assert2(!options.signatureLength || signature.length === options.signatureLength);
699
- return signature;
700
- }
701
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
702
- const verify = createVerify(options.algorithm);
703
- verify.update(blockToVerify);
704
- return verify.verify(options.publicKey, signature);
705
- }
706
- function makeSHA1Thumbprint(buffer) {
707
- return createHash("sha1").update(buffer).digest();
708
- }
709
- var RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
710
- var RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
711
- var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
712
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
713
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
714
- return PaddingAlgorithm2;
715
- })(PaddingAlgorithm || {});
716
- assert2(4 /* RSA_PKCS1_OAEP_PADDING */ === constants.RSA_PKCS1_OAEP_PADDING);
717
- assert2(1 /* RSA_PKCS1_PADDING */ === constants.RSA_PKCS1_PADDING);
718
- function publicEncrypt_native(buffer, publicKey, algorithm) {
719
- if (algorithm === void 0) {
720
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
721
- }
722
- return publicEncrypt1(
723
- {
724
- key: publicKey,
725
- padding: algorithm
726
- },
727
- buffer
728
- );
729
- }
730
- function privateDecrypt_native(buffer, privateKey, algorithm) {
731
- if (algorithm === void 0) {
732
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
733
- }
734
- try {
735
- return privateDecrypt1(
736
- {
737
- key: privateKey.hidden,
738
- padding: algorithm
739
- },
740
- buffer
741
- );
742
- } catch (err) {
743
- return Buffer.alloc(1);
744
- }
745
- }
746
- var publicEncrypt = publicEncrypt_native;
747
- var privateDecrypt = privateDecrypt_native;
748
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
749
- if (paddingAlgorithm === void 0) {
750
- paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
751
- }
752
- if (paddingAlgorithm === RSA_PKCS1_PADDING) {
753
- padding = padding || 11;
754
- if (padding !== 11) throw new Error("padding should be 11");
755
- } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
756
- padding = padding || 42;
757
- if (padding !== 42) throw new Error("padding should be 42");
758
- } else {
759
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
760
- }
761
- const chunk_size = blockSize - padding;
762
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
763
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
764
- for (let i = 0; i < nbBlocks; i++) {
765
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
766
- const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
767
- if (encrypted_chunk.length !== blockSize) {
768
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
769
- }
770
- encrypted_chunk.copy(outputBuffer, i * blockSize);
771
- }
772
- return outputBuffer;
773
- }
774
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
775
- paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
776
- if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
777
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
778
- }
779
- const nbBlocks = Math.ceil(buffer.length / blockSize);
780
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
781
- let total_length = 0;
782
- for (let i = 0; i < nbBlocks; i++) {
783
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
784
- const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
785
- decrypted_buf.copy(outputBuffer, total_length);
786
- total_length += decrypted_buf.length;
787
- }
788
- return outputBuffer.subarray(0, total_length);
789
- }
790
- function coerceCertificatePem(certificate) {
791
- if (certificate instanceof Buffer) {
792
- certificate = toPem(certificate, "CERTIFICATE");
793
- }
794
- assert2(typeof certificate === "string");
795
- return certificate;
796
- }
797
- function extractPublicKeyFromCertificateSync(certificate) {
798
- certificate = coerceCertificatePem(certificate);
799
- const key = jsrsasign.KEYUTIL.getKey(certificate);
800
- const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
801
- assert2(typeof publicKeyAsPem === "string");
802
- return publicKeyAsPem;
803
- }
804
- function extractPublicKeyFromCertificate(certificate, callback) {
805
- let err1 = null;
806
- let keyPem;
807
- try {
808
- keyPem = extractPublicKeyFromCertificateSync(certificate);
809
- } catch (err) {
810
- err1 = err;
595
+ // source/crypto_explore_certificate.ts
596
+ import assert3 from "assert";
597
+
598
+ // source/directory_name.ts
599
+ import assert2 from "assert";
600
+ function readDirectoryName(buffer, block) {
601
+ const set_blocks = readStruct(buffer, block);
602
+ const names = {};
603
+ for (const set_block of set_blocks) {
604
+ assert2(set_block.tag === 49);
605
+ const blocks = readStruct(buffer, set_block);
606
+ assert2(blocks.length === 1);
607
+ assert2(blocks[0].tag === 48);
608
+ const sequenceBlock = readStruct(buffer, blocks[0]);
609
+ assert2(sequenceBlock.length === 2);
610
+ const type = readObjectIdentifier(buffer, sequenceBlock[0]);
611
+ names[type.name] = readValue(buffer, sequenceBlock[1]);
811
612
  }
812
- setImmediate(() => {
813
- callback(err1, keyPem);
814
- });
613
+ return names;
815
614
  }
816
615
 
817
616
  // source/crypto_explore_certificate.ts
818
617
  var doDebug = false;
819
618
  function _readAttributeTypeAndValue(buffer, block) {
820
- let inner_blocks = _readStruct(buffer, block);
821
- inner_blocks = _readStruct(buffer, inner_blocks[0]);
619
+ let inner_blocks = readStruct(buffer, block);
620
+ inner_blocks = readStruct(buffer, inner_blocks[0]);
822
621
  const data = {
823
- identifier: _readObjectIdentifier(buffer, inner_blocks[0]).name,
824
- value: _readValue(buffer, inner_blocks[1])
622
+ identifier: readObjectIdentifier(buffer, inner_blocks[0]).name,
623
+ value: readValue(buffer, inner_blocks[1])
825
624
  };
826
625
  const result = {};
827
626
  for (const [key, value] of Object.entries(data)) {
@@ -830,7 +629,7 @@ function _readAttributeTypeAndValue(buffer, block) {
830
629
  return result;
831
630
  }
832
631
  function _readRelativeDistinguishedName(buffer, block) {
833
- const inner_blocks = _readStruct(buffer, block);
632
+ const inner_blocks = readStruct(buffer, block);
834
633
  const data = inner_blocks.map((block2) => _readAttributeTypeAndValue(buffer, block2));
835
634
  const result = {};
836
635
  for (const e of data) {
@@ -842,64 +641,64 @@ function _readName(buffer, block) {
842
641
  return _readRelativeDistinguishedName(buffer, block);
843
642
  }
844
643
  function _readValidity(buffer, block) {
845
- const inner_blocks = _readStruct(buffer, block);
644
+ const inner_blocks = readStruct(buffer, block);
846
645
  return {
847
- notBefore: _readTime(buffer, inner_blocks[0]),
848
- notAfter: _readTime(buffer, inner_blocks[1])
646
+ notBefore: readTime(buffer, inner_blocks[0]),
647
+ notAfter: readTime(buffer, inner_blocks[1])
849
648
  };
850
649
  }
851
650
  function _readAuthorityKeyIdentifier(buffer) {
852
651
  const block_info = readTag(buffer, 0);
853
- const blocks = _readStruct(buffer, block_info);
854
- const keyIdentifier_block = _findBlockAtIndex(blocks, 0);
855
- const authorityCertIssuer_block = _findBlockAtIndex(blocks, 1);
856
- const authorityCertSerialNumber_block = _findBlockAtIndex(blocks, 2);
652
+ const blocks = readStruct(buffer, block_info);
653
+ const keyIdentifier_block = findBlockAtIndex(blocks, 0);
654
+ const authorityCertIssuer_block = findBlockAtIndex(blocks, 1);
655
+ const authorityCertSerialNumber_block = findBlockAtIndex(blocks, 2);
857
656
  function _readAuthorityCertIssuer(block) {
858
- const inner_blocks = _readStruct(buffer, block);
859
- const directoryName_block = _findBlockAtIndex(inner_blocks, 4);
657
+ const inner_blocks = readStruct(buffer, block);
658
+ const directoryName_block = findBlockAtIndex(inner_blocks, 4);
860
659
  if (directoryName_block) {
861
- const a = _readStruct(buffer, directoryName_block);
862
- return _readDirectoryName(buffer, a[0]);
660
+ const a = readStruct(buffer, directoryName_block);
661
+ return readDirectoryName(buffer, a[0]);
863
662
  } else {
864
663
  throw new Error("Invalid _readAuthorityCertIssuer");
865
664
  }
866
665
  }
867
666
  function _readAuthorityCertIssuerFingerPrint(block) {
868
- const inner_blocks = _readStruct(buffer, block);
869
- const directoryName_block = _findBlockAtIndex(inner_blocks, 4);
667
+ const inner_blocks = readStruct(buffer, block);
668
+ const directoryName_block = findBlockAtIndex(inner_blocks, 4);
870
669
  if (!directoryName_block) {
871
670
  return "";
872
671
  }
873
- const a = _readStruct(buffer, directoryName_block);
672
+ const a = readStruct(buffer, directoryName_block);
874
673
  if (a.length < 1) {
875
674
  return "";
876
675
  }
877
- return directoryName_block ? formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, a[0]))) : "";
676
+ return directoryName_block ? formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, a[0]))) : "";
878
677
  }
879
678
  const authorityCertIssuer = authorityCertIssuer_block ? _readAuthorityCertIssuer(authorityCertIssuer_block) : null;
880
679
  const authorityCertIssuerFingerPrint = authorityCertIssuer_block ? _readAuthorityCertIssuerFingerPrint(authorityCertIssuer_block) : "";
881
680
  return {
882
681
  authorityCertIssuer,
883
682
  authorityCertIssuerFingerPrint,
884
- serial: authorityCertSerialNumber_block ? formatBuffer2DigitHexWithColum(_getBlock(buffer, authorityCertSerialNumber_block)) : null,
683
+ serial: authorityCertSerialNumber_block ? formatBuffer2DigitHexWithColum(getBlock(buffer, authorityCertSerialNumber_block)) : null,
885
684
  // can be null for self-signed cert
886
- keyIdentifier: keyIdentifier_block ? formatBuffer2DigitHexWithColum(_getBlock(buffer, keyIdentifier_block)) : null
685
+ keyIdentifier: keyIdentifier_block ? formatBuffer2DigitHexWithColum(getBlock(buffer, keyIdentifier_block)) : null
887
686
  // can be null for self-signed certf
888
687
  };
889
688
  }
890
689
  function readBasicConstraint2_5_29_19(buffer, block) {
891
690
  const block_info = readTag(buffer, 0);
892
- const inner_blocks = _readStruct(buffer, block_info).slice(0, 2);
691
+ const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
893
692
  let cA = false;
894
693
  let pathLengthConstraint = 0;
895
694
  let breakControl = 0;
896
695
  for (const inner_block of inner_blocks) {
897
696
  switch (inner_block.tag) {
898
697
  case 1 /* BOOLEAN */:
899
- cA = _readBooleanValue(buffer, inner_block);
698
+ cA = readBooleanValue(buffer, inner_block);
900
699
  break;
901
700
  case 2 /* INTEGER */:
902
- pathLengthConstraint = _readIntegerValue(buffer, inner_block);
701
+ pathLengthConstraint = readIntegerValue(buffer, inner_block);
903
702
  breakControl = 1;
904
703
  break;
905
704
  }
@@ -921,7 +720,7 @@ function _readGeneralNames(buffer, block) {
921
720
  8: { name: "registeredID", type: "OBJECT_IDENTIFIER" },
922
721
  32: { name: "otherName", type: "AnotherName" }
923
722
  };
924
- const blocks = _readStruct(buffer, block);
723
+ const blocks = readStruct(buffer, block);
925
724
  function _readFromType(buffer2, block2, type) {
926
725
  switch (type) {
927
726
  case "IA5String":
@@ -933,19 +732,19 @@ function _readGeneralNames(buffer, block) {
933
732
  const n = {};
934
733
  for (const block2 of blocks) {
935
734
  assert3((block2.tag & 128) === 128);
936
- const t = block2.tag & 127;
937
- const type = _data[t];
735
+ const t2 = block2.tag & 127;
736
+ const type = _data[t2];
938
737
  if (!type) {
939
- console.log("_readGeneralNames: INVALID TYPE => " + t + " 0x" + t.toString(16));
738
+ console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
940
739
  continue;
941
740
  }
942
- if (t == 32) {
741
+ if (t2 == 32) {
943
742
  n[type.name] = n[type.name] || [];
944
- const blocks2 = _readStruct(buffer, block2);
945
- const name = _readObjectIdentifier(buffer, blocks2[0]).name;
946
- const buf = _getBlock(buffer, blocks2[1]);
743
+ const blocks2 = readStruct(buffer, block2);
744
+ const name = readObjectIdentifier(buffer, blocks2[0]).name;
745
+ const buf = getBlock(buffer, blocks2[1]);
947
746
  const b = readTag(buf, 0);
948
- const nn = _readValue(buf, b);
747
+ const nn = readValue(buf, b);
949
748
  const data = {
950
749
  identifier: name,
951
750
  value: nn
@@ -994,7 +793,7 @@ function readKeyUsage(oid, buffer) {
994
793
  function readExtKeyUsage(oid, buffer) {
995
794
  assert3(oid === "2.5.29.37");
996
795
  const block_info = readTag(buffer, 0);
997
- const inner_blocks = _readStruct(buffer, block_info);
796
+ const inner_blocks = readStruct(buffer, block_info);
998
797
  const extKeyUsage = {
999
798
  serverAuth: false,
1000
799
  clientAuth: false,
@@ -1007,30 +806,30 @@ function readExtKeyUsage(oid, buffer) {
1007
806
  ocspSigning: false
1008
807
  };
1009
808
  for (const block of inner_blocks) {
1010
- const identifier = _readObjectIdentifier(buffer, block);
809
+ const identifier = readObjectIdentifier(buffer, block);
1011
810
  extKeyUsage[identifier.name] = true;
1012
811
  }
1013
812
  return extKeyUsage;
1014
813
  }
1015
814
  function _readSubjectPublicKey(buffer) {
1016
815
  const block_info = readTag(buffer, 0);
1017
- const blocks = _readStruct(buffer, block_info);
816
+ const blocks = readStruct(buffer, block_info);
1018
817
  return {
1019
818
  modulus: buffer.subarray(blocks[0].position + 1, blocks[0].position + blocks[0].length)
1020
819
  };
1021
820
  }
1022
- function _readExtension(buffer, block) {
1023
- const inner_blocks = _readStruct(buffer, block);
821
+ function readExtension(buffer, block) {
822
+ const inner_blocks = readStruct(buffer, block);
1024
823
  if (inner_blocks.length === 3) {
1025
824
  assert3(inner_blocks[1].tag === 1 /* BOOLEAN */);
1026
825
  inner_blocks[1] = inner_blocks[2];
1027
826
  }
1028
- const identifier = _readObjectIdentifier(buffer, inner_blocks[0]);
1029
- const buf = _getBlock(buffer, inner_blocks[1]);
827
+ const identifier = readObjectIdentifier(buffer, inner_blocks[0]);
828
+ const buf = getBlock(buffer, inner_blocks[1]);
1030
829
  let value = null;
1031
830
  switch (identifier.name) {
1032
831
  case "subjectKeyIdentifier":
1033
- value = formatBuffer2DigitHexWithColum(_readOctetString(buffer, inner_blocks[1]));
832
+ value = formatBuffer2DigitHexWithColum(readOctetString(buffer, inner_blocks[1]));
1034
833
  break;
1035
834
  case "subjectAltName":
1036
835
  value = _readSubjectAltNames(buf);
@@ -1060,9 +859,9 @@ function _readExtension(buffer, block) {
1060
859
  }
1061
860
  function _readExtensions(buffer, block) {
1062
861
  assert3(block.tag === 163);
1063
- let inner_blocks = _readStruct(buffer, block);
1064
- inner_blocks = _readStruct(buffer, inner_blocks[0]);
1065
- const extensions = inner_blocks.map((block2) => _readExtension(buffer, block2));
862
+ let inner_blocks = readStruct(buffer, block);
863
+ inner_blocks = readStruct(buffer, inner_blocks[0]);
864
+ const extensions = inner_blocks.map((block2) => readExtension(buffer, block2));
1066
865
  const result = {};
1067
866
  for (const e of extensions) {
1068
867
  result[e.identifier.name] = e.value;
@@ -1070,11 +869,11 @@ function _readExtensions(buffer, block) {
1070
869
  return result;
1071
870
  }
1072
871
  function _readSubjectPublicKeyInfo(buffer, block) {
1073
- const inner_blocks = _readStruct(buffer, block);
1074
- const algorithm = _readAlgorithmIdentifier(buffer, inner_blocks[0]);
1075
- const subjectPublicKey = _readBitString(buffer, inner_blocks[1]);
872
+ const inner_blocks = readStruct(buffer, block);
873
+ const algorithm = readAlgorithmIdentifier(buffer, inner_blocks[0]);
874
+ const subjectPublicKey = readBitString(buffer, inner_blocks[1]);
1076
875
  const data = subjectPublicKey.data;
1077
- const values = _readListOfInteger(data);
876
+ const values = readListOfInteger(data);
1078
877
  return {
1079
878
  algorithm: algorithm.identifier,
1080
879
  keyLength: values[0].length - 1,
@@ -1084,9 +883,9 @@ function _readSubjectPublicKeyInfo(buffer, block) {
1084
883
  };
1085
884
  }
1086
885
  function _readSubjectECCPublicKeyInfo(buffer, block) {
1087
- const inner_blocks = _readStruct(buffer, block);
1088
- const algorithm = _readECCAlgorithmIdentifier(buffer, inner_blocks[0]);
1089
- const subjectPublicKey = _readBitString(buffer, inner_blocks[1]);
886
+ const inner_blocks = readStruct(buffer, block);
887
+ const algorithm = readECCAlgorithmIdentifier(buffer, inner_blocks[0]);
888
+ const subjectPublicKey = readBitString(buffer, inner_blocks[1]);
1090
889
  const data = subjectPublicKey.data;
1091
890
  return {
1092
891
  algorithm: algorithm.identifier,
@@ -1097,33 +896,33 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
1097
896
  };
1098
897
  }
1099
898
  function readTbsCertificate(buffer, block) {
1100
- const blocks = _readStruct(buffer, block);
899
+ const blocks = readStruct(buffer, block);
1101
900
  let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1102
901
  let subjectPublicKeyInfo;
1103
902
  if (blocks.length === 6) {
1104
903
  version = 1;
1105
- serialNumber = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, blocks[0]));
1106
- signature = _readAlgorithmIdentifier(buffer, blocks[1]);
904
+ serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[0]));
905
+ signature = readAlgorithmIdentifier(buffer, blocks[1]);
1107
906
  issuer = _readName(buffer, blocks[2]);
1108
907
  validity = _readValidity(buffer, blocks[3]);
1109
908
  subject = _readName(buffer, blocks[4]);
1110
- subjectFingerPrint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[4])));
909
+ subjectFingerPrint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[4])));
1111
910
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[5]);
1112
911
  extensions = null;
1113
912
  } else {
1114
- const version_block = _findBlockAtIndex(blocks, 0);
913
+ const version_block = findBlockAtIndex(blocks, 0);
1115
914
  if (!version_block) {
1116
915
  throw new Error("cannot find version block");
1117
916
  }
1118
- version = _readVersionValue(buffer, version_block) + 1;
1119
- serialNumber = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, blocks[1]));
1120
- signature = _readAlgorithmIdentifier(buffer, blocks[2]);
917
+ version = readVersionValue(buffer, version_block) + 1;
918
+ serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[1]));
919
+ signature = readAlgorithmIdentifier(buffer, blocks[2]);
1121
920
  issuer = _readName(buffer, blocks[3]);
1122
921
  validity = _readValidity(buffer, blocks[4]);
1123
922
  subject = _readName(buffer, blocks[5]);
1124
- subjectFingerPrint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[5])));
1125
- const inner_block = _readStruct(buffer, blocks[6]);
1126
- const what_type = _readAlgorithmIdentifier(buffer, inner_block[0]).identifier;
923
+ subjectFingerPrint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[5])));
924
+ const inner_block = readStruct(buffer, blocks[6]);
925
+ const what_type = readAlgorithmIdentifier(buffer, inner_block[0]).identifier;
1127
926
  switch (what_type) {
1128
927
  case "rsaEncryption": {
1129
928
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
@@ -1135,7 +934,7 @@ function readTbsCertificate(buffer, block) {
1135
934
  break;
1136
935
  }
1137
936
  }
1138
- const extensionBlock = _findBlockAtIndex(blocks, 3);
937
+ const extensionBlock = findBlockAtIndex(blocks, 3);
1139
938
  if (!extensionBlock) {
1140
939
  doDebug && console.log("X509 certificate is invalid : cannot find extension block version =" + version_block);
1141
940
  extensions = null;
@@ -1159,11 +958,11 @@ function exploreCertificate(certificate) {
1159
958
  assert3(certificate instanceof Buffer);
1160
959
  if (!certificate._exploreCertificate_cache) {
1161
960
  const block_info = readTag(certificate, 0);
1162
- const blocks = _readStruct(certificate, block_info);
961
+ const blocks = readStruct(certificate, block_info);
1163
962
  certificate._exploreCertificate_cache = {
1164
963
  tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1165
- signatureAlgorithm: _readAlgorithmIdentifier(certificate, blocks[1]),
1166
- signatureValue: _readSignatureValue(certificate, blocks[2])
964
+ signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
965
+ signatureValue: readSignatureValue(certificate, blocks[2])
1167
966
  };
1168
967
  }
1169
968
  return certificate._exploreCertificate_cache;
@@ -1193,34 +992,394 @@ function combine_der(certificates) {
1193
992
  return Buffer.concat(certificates);
1194
993
  }
1195
994
 
1196
- // source/explore_certificate.ts
1197
- import assert4 from "assert";
1198
- function coerceCertificate(certificate) {
1199
- if (typeof certificate === "string") {
1200
- certificate = convertPEMtoDER(certificate);
995
+ // source/crypto_utils.ts
996
+ import jsrsasign from "jsrsasign";
997
+ var { hexy } = pkg_hexy;
998
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
999
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
1000
+ function identifyPemType(rawKey) {
1001
+ if (rawKey instanceof Buffer) {
1002
+ rawKey = rawKey.toString("utf8");
1201
1003
  }
1202
- assert4(certificate instanceof Buffer);
1203
- return certificate;
1004
+ const match = PEM_TYPE_REGEX.exec(rawKey);
1005
+ return !match ? void 0 : match[2];
1204
1006
  }
1205
- function exploreCertificateInfo(certificate) {
1206
- certificate = coerceCertificate(certificate);
1207
- const certInfo = exploreCertificate(certificate);
1208
- const data = {
1209
- publicKeyLength: certInfo.tbsCertificate.subjectPublicKeyInfo.keyLength,
1210
- notBefore: certInfo.tbsCertificate.validity.notBefore,
1211
- notAfter: certInfo.tbsCertificate.validity.notAfter,
1212
- publicKey: certInfo.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey,
1213
- subject: certInfo.tbsCertificate.subject
1214
- };
1215
- if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1216
- throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1007
+ function removeTrailingLF(str) {
1008
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1009
+ return tmp;
1010
+ }
1011
+ function toPem(raw_key, pem) {
1012
+ assert4(raw_key, "expecting a key");
1013
+ assert4(typeof pem === "string");
1014
+ let pemType = identifyPemType(raw_key);
1015
+ if (pemType) {
1016
+ return raw_key instanceof Buffer ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1017
+ } else {
1018
+ pemType = pem;
1019
+ assert4(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1020
+ let b = raw_key.toString("base64");
1021
+ let str = "-----BEGIN " + pemType + "-----\n";
1022
+ while (b.length) {
1023
+ str += b.substring(0, 64) + "\n";
1024
+ b = b.substring(64);
1025
+ }
1026
+ str += "-----END " + pemType + "-----";
1027
+ return str;
1217
1028
  }
1218
- return data;
1219
1029
  }
1220
-
1221
- // source/derived_keys.ts
1030
+ function convertPEMtoDER(raw_key) {
1031
+ let match;
1032
+ let pemType;
1033
+ let base64str;
1034
+ const parts = [];
1035
+ PEM_REGEX.lastIndex = 0;
1036
+ while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1037
+ pemType = match[2];
1038
+ base64str = match[3];
1039
+ base64str = base64str.replace(/\r?\n/g, "");
1040
+ parts.push(Buffer.from(base64str, "base64"));
1041
+ }
1042
+ return combine_der(parts);
1043
+ }
1044
+ function hexDump(buffer, width) {
1045
+ if (!buffer) {
1046
+ return "<>";
1047
+ }
1048
+ width = width || 32;
1049
+ if (buffer.length > 1024) {
1050
+ return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1051
+ } else {
1052
+ return hexy(buffer, { width, format: "twos" });
1053
+ }
1054
+ }
1055
+ function makeMessageChunkSignature(chunk, options) {
1056
+ const signer = createSign(options.algorithm);
1057
+ signer.update(chunk);
1058
+ const signature = signer.sign(options.privateKey.hidden);
1059
+ assert4(!options.signatureLength || signature.length === options.signatureLength);
1060
+ return signature;
1061
+ }
1062
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
1063
+ const verify = createVerify(options.algorithm);
1064
+ verify.update(blockToVerify);
1065
+ return verify.verify(options.publicKey, signature);
1066
+ }
1067
+ function makeSHA1Thumbprint(buffer) {
1068
+ return createHash("sha1").update(buffer).digest();
1069
+ }
1070
+ var RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
1071
+ var RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
1072
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1073
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1074
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1075
+ return PaddingAlgorithm2;
1076
+ })(PaddingAlgorithm || {});
1077
+ assert4(4 /* RSA_PKCS1_OAEP_PADDING */ === constants.RSA_PKCS1_OAEP_PADDING);
1078
+ assert4(1 /* RSA_PKCS1_PADDING */ === constants.RSA_PKCS1_PADDING);
1079
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
1080
+ if (algorithm === void 0) {
1081
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1082
+ }
1083
+ return publicEncrypt1(
1084
+ {
1085
+ key: publicKey,
1086
+ padding: algorithm
1087
+ },
1088
+ buffer
1089
+ );
1090
+ }
1091
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
1092
+ if (algorithm === void 0) {
1093
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1094
+ }
1095
+ try {
1096
+ return privateDecrypt1(
1097
+ {
1098
+ key: privateKey.hidden,
1099
+ padding: algorithm
1100
+ },
1101
+ buffer
1102
+ );
1103
+ } catch (err) {
1104
+ return Buffer.alloc(1);
1105
+ }
1106
+ }
1107
+ var publicEncrypt = publicEncrypt_native;
1108
+ var privateDecrypt = privateDecrypt_native;
1109
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1110
+ if (paddingAlgorithm === void 0) {
1111
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1112
+ }
1113
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1114
+ padding = padding || 11;
1115
+ if (padding !== 11) throw new Error("padding should be 11");
1116
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1117
+ padding = padding || 42;
1118
+ if (padding !== 42) throw new Error("padding should be 42");
1119
+ } else {
1120
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1121
+ }
1122
+ const chunk_size = blockSize - padding;
1123
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
1124
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1125
+ for (let i = 0; i < nbBlocks; i++) {
1126
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1127
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1128
+ if (encrypted_chunk.length !== blockSize) {
1129
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1130
+ }
1131
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
1132
+ }
1133
+ return outputBuffer;
1134
+ }
1135
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1136
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1137
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1138
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1139
+ }
1140
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
1141
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1142
+ let total_length = 0;
1143
+ for (let i = 0; i < nbBlocks; i++) {
1144
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1145
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1146
+ decrypted_buf.copy(outputBuffer, total_length);
1147
+ total_length += decrypted_buf.length;
1148
+ }
1149
+ return outputBuffer.subarray(0, total_length);
1150
+ }
1151
+ function coerceCertificatePem(certificate) {
1152
+ if (certificate instanceof Buffer) {
1153
+ certificate = toPem(certificate, "CERTIFICATE");
1154
+ }
1155
+ assert4(typeof certificate === "string");
1156
+ return certificate;
1157
+ }
1158
+ function extractPublicKeyFromCertificateSync(certificate) {
1159
+ certificate = coerceCertificatePem(certificate);
1160
+ const key = jsrsasign.KEYUTIL.getKey(certificate);
1161
+ const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
1162
+ assert4(typeof publicKeyAsPem === "string");
1163
+ return publicKeyAsPem;
1164
+ }
1165
+ function extractPublicKeyFromCertificate(certificate, callback) {
1166
+ let err1 = null;
1167
+ let keyPem;
1168
+ try {
1169
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
1170
+ } catch (err) {
1171
+ err1 = err;
1172
+ }
1173
+ setImmediate(() => {
1174
+ callback(err1, keyPem);
1175
+ });
1176
+ }
1177
+
1178
+ // source/explore_private_key.ts
1179
+ function f(buffer, b) {
1180
+ return buffer.subarray(b.position + 1, b.position + b.length);
1181
+ }
1182
+ var doDebug2 = !!process.env.DEBUG;
1183
+ function explorePrivateKey(privateKey2) {
1184
+ const privateKey1 = privateKey2.hidden;
1185
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1186
+ const block_info = readTag(privateKey, 0);
1187
+ const blocks = readStruct(privateKey, block_info);
1188
+ if (blocks.length === 9) {
1189
+ const version2 = f(privateKey, blocks[0]);
1190
+ const modulus2 = f(privateKey, blocks[1]);
1191
+ const publicExponent2 = f(privateKey, blocks[2]);
1192
+ const privateExponent2 = f(privateKey, blocks[3]);
1193
+ const prime12 = f(privateKey, blocks[4]);
1194
+ const prime22 = f(privateKey, blocks[5]);
1195
+ const exponent12 = f(privateKey, blocks[6]);
1196
+ const exponent22 = f(privateKey, blocks[7]);
1197
+ return {
1198
+ version: version2,
1199
+ modulus: modulus2,
1200
+ publicExponent: publicExponent2,
1201
+ privateExponent: privateExponent2,
1202
+ prime1: prime12,
1203
+ prime2: prime22,
1204
+ exponent1: exponent12,
1205
+ exponent2: exponent22
1206
+ };
1207
+ }
1208
+ if (doDebug2) {
1209
+ console.log("-------------------- private key:");
1210
+ console.log(block_info);
1211
+ console.log(
1212
+ blocks.map((b2) => ({
1213
+ tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1214
+ l: b2.length,
1215
+ p: b2.position,
1216
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1217
+ }))
1218
+ );
1219
+ }
1220
+ const b = blocks[2];
1221
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1222
+ const block_info1 = readTag(bb, 0);
1223
+ const blocks1 = readStruct(bb, block_info1);
1224
+ if (doDebug2) {
1225
+ console.log(
1226
+ blocks1.map((b2) => ({
1227
+ tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1228
+ l: b2.length,
1229
+ p: b2.position,
1230
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1231
+ }))
1232
+ );
1233
+ }
1234
+ const version = f(bb, blocks1[0]);
1235
+ const modulus = f(bb, blocks1[1]);
1236
+ const publicExponent = f(bb, blocks1[2]);
1237
+ const privateExponent = f(bb, blocks1[3]);
1238
+ const prime1 = f(bb, blocks1[4]);
1239
+ const prime2 = f(bb, blocks1[5]);
1240
+ const exponent1 = f(bb, blocks1[6]);
1241
+ const exponent2 = f(bb, blocks1[7]);
1242
+ return {
1243
+ version,
1244
+ modulus,
1245
+ publicExponent,
1246
+ privateExponent,
1247
+ prime1,
1248
+ prime2,
1249
+ exponent1,
1250
+ exponent2
1251
+ };
1252
+ }
1253
+
1254
+ // source/public_private_match.ts
1255
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1256
+ const i = exploreCertificate(certificate);
1257
+ const j = explorePrivateKey(privateKey);
1258
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1259
+ const modulus2 = j.modulus;
1260
+ if (modulus1.length != modulus2.length) {
1261
+ return false;
1262
+ }
1263
+ return modulus1.toString("hex") === modulus2.toString("hex");
1264
+ }
1265
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1266
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1267
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1268
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1269
+ const finalString = decryptedBuffer.toString("utf-8");
1270
+ return initialBuffer.toString("utf-8") === finalString;
1271
+ }
1272
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1273
+ const e = explorePrivateKey(privateKey);
1274
+ const blockSize = e.modulus.length;
1275
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1276
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1277
+ }
1278
+
1279
+ // source/common.ts
1280
+ import __crypto from "crypto";
1281
+ var KeyObjectOrig = __crypto.KeyObject;
1282
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = __crypto;
1283
+ function isKeyObject(mayBeKeyObject) {
1284
+ if (KeyObjectOrig) {
1285
+ return mayBeKeyObject instanceof KeyObjectOrig;
1286
+ }
1287
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1288
+ }
1289
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1290
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1291
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1292
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1293
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1294
+ return CertificatePurpose2;
1295
+ })(CertificatePurpose || {});
1296
+
1297
+ // source/crypto_utils2.ts
1222
1298
  import assert5 from "assert";
1299
+ import jsrsasign2 from "jsrsasign";
1300
+ function rsaLengthPrivateKey(key) {
1301
+ const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
1302
+ const a = jsrsasign2.KEYUTIL.getKey(keyPem);
1303
+ return a.n.toString(16).length / 2;
1304
+ }
1305
+ function toPem2(raw_key, pem) {
1306
+ if (raw_key.hidden) {
1307
+ return toPem2(raw_key.hidden, pem);
1308
+ }
1309
+ assert5(raw_key, "expecting a key");
1310
+ assert5(typeof pem === "string");
1311
+ if (isKeyObject(raw_key)) {
1312
+ const _raw_key = raw_key;
1313
+ if (pem === "RSA PRIVATE KEY") {
1314
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs1" }).toString());
1315
+ } else if (pem === "PRIVATE KEY") {
1316
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs8" }).toString());
1317
+ } else {
1318
+ throw new Error("Unsupported case!");
1319
+ }
1320
+ }
1321
+ return toPem(raw_key, pem);
1322
+ }
1323
+ function coercePrivateKeyPem(privateKey) {
1324
+ return toPem2(privateKey, "PRIVATE KEY");
1325
+ }
1326
+ function coercePublicKeyPem(publicKey) {
1327
+ if (isKeyObject(publicKey)) {
1328
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1329
+ }
1330
+ assert5(typeof publicKey === "string");
1331
+ return publicKey;
1332
+ }
1333
+ function coerceRsaPublicKeyPem(publicKey) {
1334
+ if (isKeyObject(publicKey)) {
1335
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1336
+ }
1337
+ assert5(typeof publicKey === "string");
1338
+ return publicKey;
1339
+ }
1340
+ function rsaLengthPublicKey(key) {
1341
+ key = coercePublicKeyPem(key);
1342
+ assert5(typeof key === "string");
1343
+ const a = jsrsasign2.KEYUTIL.getKey(key);
1344
+ return a.n.toString(16).length / 2;
1345
+ }
1346
+ function rsaLengthRsaPublicKey(key) {
1347
+ key = coerceRsaPublicKeyPem(key);
1348
+ assert5(typeof key === "string");
1349
+ const a = jsrsasign2.KEYUTIL.getKey(key);
1350
+ return a.n.toString(16).length / 2;
1351
+ }
1352
+
1353
+ // source/derived_keys.ts
1354
+ import assert7 from "assert";
1223
1355
  import { createCipheriv, createDecipheriv, createHmac } from "crypto";
1356
+
1357
+ // source/explore_certificate.ts
1358
+ import assert6 from "assert";
1359
+ function coerceCertificate(certificate) {
1360
+ if (typeof certificate === "string") {
1361
+ certificate = convertPEMtoDER(certificate);
1362
+ }
1363
+ assert6(certificate instanceof Buffer);
1364
+ return certificate;
1365
+ }
1366
+ function exploreCertificateInfo(certificate) {
1367
+ certificate = coerceCertificate(certificate);
1368
+ const certInfo = exploreCertificate(certificate);
1369
+ const data = {
1370
+ publicKeyLength: certInfo.tbsCertificate.subjectPublicKeyInfo.keyLength,
1371
+ notBefore: certInfo.tbsCertificate.validity.notBefore,
1372
+ notAfter: certInfo.tbsCertificate.validity.notAfter,
1373
+ publicKey: certInfo.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey,
1374
+ subject: certInfo.tbsCertificate.subject
1375
+ };
1376
+ if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1377
+ throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1378
+ }
1379
+ return data;
1380
+ }
1381
+
1382
+ // source/derived_keys.ts
1224
1383
  function HMAC_HASH(sha1or256, secret, message) {
1225
1384
  return createHmac(sha1or256, secret).update(message).digest();
1226
1385
  }
@@ -1228,8 +1387,8 @@ function plus(buf1, buf2) {
1228
1387
  return Buffer.concat([buf1, buf2]);
1229
1388
  }
1230
1389
  function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1231
- assert5(seed instanceof Buffer);
1232
- assert5(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1390
+ assert7(seed instanceof Buffer);
1391
+ assert7(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1233
1392
  const a = [];
1234
1393
  a[0] = seed;
1235
1394
  let index = 1;
@@ -1242,12 +1401,12 @@ function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1242
1401
  return p_hash.subarray(0, minLength);
1243
1402
  }
1244
1403
  function computeDerivedKeys(secret, seed, options) {
1245
- assert5(Number.isFinite(options.signatureLength));
1246
- assert5(Number.isFinite(options.encryptingKeyLength));
1247
- assert5(Number.isFinite(options.encryptingBlockSize));
1248
- assert5(typeof options.algorithm === "string");
1404
+ assert7(Number.isFinite(options.signatureLength));
1405
+ assert7(Number.isFinite(options.encryptingKeyLength));
1406
+ assert7(Number.isFinite(options.encryptingBlockSize));
1407
+ assert7(typeof options.algorithm === "string");
1249
1408
  options.sha1or256 = options.sha1or256 || "SHA1";
1250
- assert5(typeof options.sha1or256 === "string");
1409
+ assert7(typeof options.sha1or256 === "string");
1251
1410
  const offset1 = options.signingKeyLength;
1252
1411
  const offset2 = offset1 + options.encryptingKeyLength;
1253
1412
  const minLength = offset2 + options.encryptingBlockSize;
@@ -1272,7 +1431,7 @@ function removePadding(buffer) {
1272
1431
  return reduceLength(buffer, nbPaddingBytes);
1273
1432
  }
1274
1433
  function verifyChunkSignature(chunk, options) {
1275
- assert5(chunk instanceof Buffer);
1434
+ assert7(chunk instanceof Buffer);
1276
1435
  let signatureLength = options.signatureLength || 0;
1277
1436
  if (signatureLength === 0) {
1278
1437
  const cert = exploreCertificateInfo(options.publicKey);
@@ -1283,16 +1442,16 @@ function verifyChunkSignature(chunk, options) {
1283
1442
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1284
1443
  }
1285
1444
  function computePaddingFooter(buffer, derivedKeys) {
1286
- assert5(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1445
+ assert7(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1287
1446
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1288
1447
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1289
1448
  padding.fill(paddingSize);
1290
1449
  return padding;
1291
1450
  }
1292
1451
  function derivedKeys_algorithm(derivedKeys) {
1293
- assert5(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1452
+ assert7(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1294
1453
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1295
- assert5(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1454
+ assert7(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1296
1455
  return algorithm;
1297
1456
  }
1298
1457
  function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
@@ -1304,199 +1463,104 @@ function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
1304
1463
  const encrypted_chunks = [];
1305
1464
  encrypted_chunks.push(cipher.update(buffer));
1306
1465
  encrypted_chunks.push(cipher.final());
1307
- return Buffer.concat(encrypted_chunks);
1308
- }
1309
- function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1310
- const algorithm = derivedKeys_algorithm(derivedKeys);
1311
- const key = derivedKeys.encryptingKey;
1312
- const initVector = derivedKeys.initializationVector;
1313
- const cipher = createDecipheriv(algorithm, key, initVector);
1314
- cipher.setAutoPadding(false);
1315
- const decrypted_chunks = [];
1316
- decrypted_chunks.push(cipher.update(buffer));
1317
- decrypted_chunks.push(cipher.final());
1318
- return Buffer.concat(decrypted_chunks);
1319
- }
1320
- function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1321
- assert5(message instanceof Buffer);
1322
- assert5(derivedKeys.signingKey instanceof Buffer);
1323
- assert5(typeof derivedKeys.sha1or256 === "string");
1324
- assert5(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1325
- const signature = createHmac(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1326
- assert5(signature.length === derivedKeys.signatureLength);
1327
- return signature;
1328
- }
1329
- function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
1330
- const message = chunk.subarray(0, chunk.length - derivedKeys.signatureLength);
1331
- const expectedSignature = chunk.subarray(chunk.length - derivedKeys.signatureLength);
1332
- const computedSignature = makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys);
1333
- return computedSignature.toString("hex") === expectedSignature.toString("hex");
1334
- }
1335
-
1336
- // source/crypto_utils2.ts
1337
- import assert6 from "assert";
1338
- import jsrsasign2 from "jsrsasign";
1339
- function rsaLengthPrivateKey(key) {
1340
- const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
1341
- const a = jsrsasign2.KEYUTIL.getKey(keyPem);
1342
- return a.n.toString(16).length / 2;
1343
- }
1344
- function toPem2(raw_key, pem) {
1345
- if (raw_key.hidden) {
1346
- return toPem2(raw_key.hidden, pem);
1347
- }
1348
- assert6(raw_key, "expecting a key");
1349
- assert6(typeof pem === "string");
1350
- if (isKeyObject(raw_key)) {
1351
- const _raw_key = raw_key;
1352
- if (pem === "RSA PRIVATE KEY") {
1353
- return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs1" }).toString());
1354
- } else if (pem === "PRIVATE KEY") {
1355
- return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs8" }).toString());
1356
- } else {
1357
- throw new Error("Unsupported case!");
1358
- }
1359
- }
1360
- return toPem(raw_key, pem);
1361
- }
1362
- function coercePrivateKeyPem(privateKey) {
1363
- return toPem2(privateKey, "PRIVATE KEY");
1364
- }
1365
- function coercePublicKeyPem(publicKey) {
1366
- if (isKeyObject(publicKey)) {
1367
- return publicKey.export({ format: "pem", type: "spki" }).toString();
1368
- }
1369
- assert6(typeof publicKey === "string");
1370
- return publicKey;
1371
- }
1372
- function coerceRsaPublicKeyPem(publicKey) {
1373
- if (isKeyObject(publicKey)) {
1374
- return publicKey.export({ format: "pem", type: "spki" }).toString();
1375
- }
1376
- assert6(typeof publicKey === "string");
1377
- return publicKey;
1378
- }
1379
- function rsaLengthPublicKey(key) {
1380
- key = coercePublicKeyPem(key);
1381
- assert6(typeof key === "string");
1382
- const a = jsrsasign2.KEYUTIL.getKey(key);
1383
- return a.n.toString(16).length / 2;
1384
- }
1385
- function rsaLengthRsaPublicKey(key) {
1386
- key = coerceRsaPublicKeyPem(key);
1387
- assert6(typeof key === "string");
1388
- const a = jsrsasign2.KEYUTIL.getKey(key);
1389
- return a.n.toString(16).length / 2;
1466
+ return Buffer.concat(encrypted_chunks);
1390
1467
  }
1391
-
1392
- // source/verify_certificate_signature.ts
1393
- import { createVerify as createVerify2 } from "crypto";
1394
- function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1395
- const block_info = readTag(certificateOrCrl, 0);
1396
- const blocks = _readStruct(certificateOrCrl, block_info);
1397
- const bufferToBeSigned = certificateOrCrl.subarray(block_info.position, blocks[1].position - 2);
1398
- const signatureAlgorithm = _readAlgorithmIdentifier(certificateOrCrl, blocks[1]);
1399
- const signatureValue = _readSignatureValueBin(certificateOrCrl, blocks[2]);
1400
- const p = split_der(parentCertificate)[0];
1401
- const certPem = toPem(p, "CERTIFICATE");
1402
- const verify = createVerify2(signatureAlgorithm.identifier);
1403
- verify.update(bufferToBeSigned);
1404
- verify.end();
1405
- return verify.verify(certPem, signatureValue);
1468
+ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1469
+ const algorithm = derivedKeys_algorithm(derivedKeys);
1470
+ const key = derivedKeys.encryptingKey;
1471
+ const initVector = derivedKeys.initializationVector;
1472
+ const cipher = createDecipheriv(algorithm, key, initVector);
1473
+ cipher.setAutoPadding(false);
1474
+ const decrypted_chunks = [];
1475
+ decrypted_chunks.push(cipher.update(buffer));
1476
+ decrypted_chunks.push(cipher.final());
1477
+ return Buffer.concat(decrypted_chunks);
1406
1478
  }
1407
- function verifyCertificateSignature(certificate, parentCertificate) {
1408
- return verifyCertificateOrClrSignature(certificate, parentCertificate);
1479
+ function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1480
+ assert7(message instanceof Buffer);
1481
+ assert7(derivedKeys.signingKey instanceof Buffer);
1482
+ assert7(typeof derivedKeys.sha1or256 === "string");
1483
+ assert7(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1484
+ const signature = createHmac(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1485
+ assert7(signature.length === derivedKeys.signatureLength);
1486
+ return signature;
1409
1487
  }
1410
- function verifyCertificateRevocationListSignature(certificateRevocationList, parentCertificate) {
1411
- return verifyCertificateOrClrSignature(certificateRevocationList, parentCertificate);
1488
+ function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
1489
+ const message = chunk.subarray(0, chunk.length - derivedKeys.signatureLength);
1490
+ const expectedSignature = chunk.subarray(chunk.length - derivedKeys.signatureLength);
1491
+ const computedSignature = makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys);
1492
+ return computedSignature.toString("hex") === expectedSignature.toString("hex");
1412
1493
  }
1413
- async function verifyCertificateChain(certificateChain) {
1414
- for (let index = 1; index < certificateChain.length; index++) {
1415
- const cert = certificateChain[index - 1];
1416
- const certParent = certificateChain[index];
1417
- const certParentInfo = exploreCertificate(certParent);
1418
- const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1419
- if (!keyUsage.keyCertSign) {
1420
- return {
1421
- status: "BadCertificateIssuerUseNotAllowed",
1422
- reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
1423
- };
1424
- }
1425
- const parentSignChild = verifyCertificateSignature(cert, certParent);
1426
- if (!parentSignChild) {
1427
- return {
1428
- status: "BadCertificateInvalid",
1429
- reason: "One of the certificate in the chain is not signing the previous certificate"
1430
- };
1431
- }
1432
- const certInfo = exploreCertificate(cert);
1433
- if (!certInfo.tbsCertificate.extensions) {
1434
- return {
1435
- status: "BadCertificateInvalid",
1436
- reason: "Cannot find X409 Extension 3 in certificate"
1437
- };
1438
- }
1439
- if (!certParentInfo.tbsCertificate.extensions || !certInfo.tbsCertificate.extensions.authorityKeyIdentifier) {
1440
- return {
1441
- status: "BadCertificateInvalid",
1442
- reason: "Cannot find X409 Extension 3 in certificate (parent)"
1443
- };
1444
- }
1445
- if (certParentInfo.tbsCertificate.extensions.subjectKeyIdentifier !== certInfo.tbsCertificate.extensions.authorityKeyIdentifier.keyIdentifier) {
1446
- return {
1447
- status: "BadCertificateInvalid",
1448
- reason: "subjectKeyIdentifier authorityKeyIdentifier in child certificate do not match subjectKeyIdentifier of parent certificate"
1449
- };
1494
+
1495
+ // source/explore_asn1.ts
1496
+ function t(tag) {
1497
+ return TagType[tag];
1498
+ }
1499
+ function bi(blockInfo, depth) {
1500
+ const indent = " ".repeat(depth);
1501
+ const hl = blockInfo.position - blockInfo.start;
1502
+ return `${blockInfo.start.toString().padStart(5, " ")}:d=${depth} hl=${hl.toString().padEnd(3, " ")} l=${blockInfo.length.toString().padStart(6, " ")} ${blockInfo.tag.toString(16).padEnd(2, " ")} ${indent} ${t(blockInfo.tag)}`;
1503
+ }
1504
+ function exploreAsn1(buffer) {
1505
+ console.log(hexDump(buffer));
1506
+ function dump(offset, depth) {
1507
+ const blockInfo = readTag(buffer, offset);
1508
+ dumpBlock(blockInfo, depth);
1509
+ function dumpBlock(blockInfo2, depth2) {
1510
+ console.log(bi(blockInfo2, depth2));
1511
+ if (blockInfo2.tag === 48 /* SEQUENCE */ || blockInfo2.tag === 49 /* SET */ || blockInfo2.tag >= 160 /* CONTEXT_SPECIFIC0 */) {
1512
+ const blocks = readStruct(buffer, blockInfo2);
1513
+ for (const block of blocks) {
1514
+ dumpBlock(block, depth2 + 1);
1515
+ }
1516
+ }
1450
1517
  }
1451
1518
  }
1452
- return {
1453
- status: "Good",
1454
- reason: `certificate chain is valid(length = ${certificateChain.length})`
1455
- };
1519
+ dump(0, 0);
1456
1520
  }
1457
1521
 
1458
1522
  // source/explore_certificate_revocation_list.ts
1459
1523
  function readNameForCrl(buffer, block) {
1460
- return _readDirectoryName(buffer, block);
1524
+ return readDirectoryName(buffer, block);
1461
1525
  }
1462
1526
  function _readTbsCertList(buffer, blockInfo) {
1463
- const blocks = _readStruct(buffer, blockInfo);
1527
+ const blocks = readStruct(buffer, blockInfo);
1464
1528
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1465
1529
  if (hasOptionalVersion) {
1466
- const version = _readIntegerValue(buffer, blocks[0]);
1467
- const signature = _readAlgorithmIdentifier(buffer, blocks[1]);
1530
+ const version = readIntegerValue(buffer, blocks[0]);
1531
+ const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1468
1532
  const issuer = readNameForCrl(buffer, blocks[2]);
1469
- const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[2])));
1470
- const thisUpdate = _readTime(buffer, blocks[3]);
1471
- const nextUpdate = _readTime(buffer, blocks[4]);
1533
+ const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[2])));
1534
+ const thisUpdate = readTime(buffer, blocks[3]);
1535
+ const nextUpdate = readTime(buffer, blocks[4]);
1472
1536
  const revokedCertificates = [];
1473
1537
  if (blocks[5] && blocks[5].tag < 128) {
1474
- const list = _readStruct(buffer, blocks[5]);
1538
+ const list = readStruct(buffer, blocks[5]);
1475
1539
  for (const r of list) {
1476
- const rr = _readStruct(buffer, r);
1477
- const userCertificate = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, rr[0]));
1478
- const revocationDate = _readTime(buffer, rr[1]);
1540
+ const rr = readStruct(buffer, r);
1541
+ const userCertificate = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, rr[0]));
1542
+ const revocationDate = readTime(buffer, rr[1]);
1479
1543
  revokedCertificates.push({
1480
1544
  revocationDate,
1481
1545
  userCertificate
1482
1546
  });
1483
1547
  }
1484
1548
  }
1485
- const ext0 = _findBlockAtIndex(blocks, 0);
1549
+ const ext0 = findBlockAtIndex(blocks, 0);
1486
1550
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1487
1551
  } else {
1488
- const signature = _readAlgorithmIdentifier(buffer, blocks[0]);
1552
+ const signature = readAlgorithmIdentifier(buffer, blocks[0]);
1489
1553
  const issuer = readNameForCrl(buffer, blocks[1]);
1490
- const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[1])));
1491
- const thisUpdate = _readTime(buffer, blocks[2]);
1492
- const nextUpdate = _readTime(buffer, blocks[3]);
1554
+ const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[1])));
1555
+ const thisUpdate = readTime(buffer, blocks[2]);
1556
+ const nextUpdate = readTime(buffer, blocks[3]);
1493
1557
  const revokedCertificates = [];
1494
1558
  if (blocks[4] && blocks[4].tag < 128) {
1495
- const list = _readStruct(buffer, blocks[4]);
1559
+ const list = readStruct(buffer, blocks[4]);
1496
1560
  for (const r of list) {
1497
- const rr = _readStruct(buffer, r);
1498
- const userCertificate = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, rr[0]));
1499
- const revocationDate = _readTime(buffer, rr[1]);
1561
+ const rr = readStruct(buffer, r);
1562
+ const userCertificate = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, rr[0]));
1563
+ const revocationDate = readTime(buffer, rr[1]);
1500
1564
  revokedCertificates.push({
1501
1565
  revocationDate,
1502
1566
  userCertificate
@@ -1508,18 +1572,18 @@ function _readTbsCertList(buffer, blockInfo) {
1508
1572
  }
1509
1573
  function exploreCertificateRevocationList(crl) {
1510
1574
  const blockInfo = readTag(crl, 0);
1511
- const blocks = _readStruct(crl, blockInfo);
1575
+ const blocks = readStruct(crl, blockInfo);
1512
1576
  const tbsCertList = _readTbsCertList(crl, blocks[0]);
1513
- const signatureAlgorithm = _readAlgorithmIdentifier(crl, blocks[1]);
1514
- const signatureValue = _readSignatureValueBin(crl, blocks[2]);
1577
+ const signatureAlgorithm = readAlgorithmIdentifier(crl, blocks[1]);
1578
+ const signatureValue = readSignatureValueBin(crl, blocks[2]);
1515
1579
  return { tbsCertList, signatureAlgorithm, signatureValue };
1516
1580
  }
1517
1581
 
1518
1582
  // source/explore_certificate_signing_request.ts
1519
1583
  function _readExtensionRequest(buffer) {
1520
1584
  const block = readTag(buffer, 0);
1521
- const inner_blocks = _readStruct(buffer, block);
1522
- const extensions = inner_blocks.map((block1) => _readExtension(buffer, block1));
1585
+ const inner_blocks = readStruct(buffer, block);
1586
+ const extensions = inner_blocks.map((block1) => readExtension(buffer, block1));
1523
1587
  const result = {};
1524
1588
  for (const e of extensions) {
1525
1589
  result[e.identifier.name] = e.value;
@@ -1528,204 +1592,39 @@ function _readExtensionRequest(buffer) {
1528
1592
  return { basicConstraints, keyUsage, subjectAltName };
1529
1593
  }
1530
1594
  function readCertificationRequestInfo(buffer, block) {
1531
- const blocks = _readStruct(buffer, block);
1595
+ const blocks = readStruct(buffer, block);
1532
1596
  if (blocks.length === 4) {
1533
- const extensionRequestBlock = _findBlockAtIndex(blocks, 0);
1597
+ const extensionRequestBlock = findBlockAtIndex(blocks, 0);
1534
1598
  if (!extensionRequestBlock) {
1535
1599
  throw new Error("cannot find extensionRequest block");
1536
1600
  }
1537
- const blocks1 = _readStruct(buffer, extensionRequestBlock);
1538
- const blocks2 = _readStruct(buffer, blocks1[0]);
1539
- const identifier = _readObjectIdentifier(buffer, blocks2[0]);
1601
+ const blocks1 = readStruct(buffer, extensionRequestBlock);
1602
+ const blocks2 = readStruct(buffer, blocks1[0]);
1603
+ const identifier = readObjectIdentifier(buffer, blocks2[0]);
1540
1604
  if (identifier.name !== "extensionRequest") {
1541
1605
  throw new Error(" Cannot find extension Request in ASN1 block");
1542
1606
  }
1543
- const buf = _getBlock(buffer, blocks2[1]);
1607
+ const buf = getBlock(buffer, blocks2[1]);
1544
1608
  const extensionRequest = _readExtensionRequest(buf);
1545
- return { extensionRequest };
1546
- }
1547
- throw new Error("Invalid CSR or ");
1548
- }
1549
- function exploreCertificateSigningRequest(crl) {
1550
- const blockInfo = readTag(crl, 0);
1551
- const blocks = _readStruct(crl, blockInfo);
1552
- const csrInfo = readCertificationRequestInfo(crl, blocks[0]);
1553
- return csrInfo;
1554
- }
1555
-
1556
- // source/explore_private_key.ts
1557
- function f(buffer, b) {
1558
- return buffer.subarray(b.position + 1, b.position + b.length);
1559
- }
1560
- var doDebug2 = !!process.env.DEBUG;
1561
- function explorePrivateKey(privateKey2) {
1562
- const privateKey1 = privateKey2.hidden;
1563
- const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1564
- const block_info = readTag(privateKey, 0);
1565
- const blocks = _readStruct(privateKey, block_info);
1566
- if (blocks.length === 9) {
1567
- const version2 = f(privateKey, blocks[0]);
1568
- const modulus2 = f(privateKey, blocks[1]);
1569
- const publicExponent2 = f(privateKey, blocks[2]);
1570
- const privateExponent2 = f(privateKey, blocks[3]);
1571
- const prime12 = f(privateKey, blocks[4]);
1572
- const prime22 = f(privateKey, blocks[5]);
1573
- const exponent12 = f(privateKey, blocks[6]);
1574
- const exponent22 = f(privateKey, blocks[7]);
1575
- return {
1576
- version: version2,
1577
- modulus: modulus2,
1578
- publicExponent: publicExponent2,
1579
- privateExponent: privateExponent2,
1580
- prime1: prime12,
1581
- prime2: prime22,
1582
- exponent1: exponent12,
1583
- exponent2: exponent22
1584
- };
1585
- }
1586
- if (doDebug2) {
1587
- console.log("-------------------- private key:");
1588
- console.log(block_info);
1589
- console.log(
1590
- blocks.map((b2) => ({
1591
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1592
- l: b2.length,
1593
- p: b2.position,
1594
- buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1595
- }))
1596
- );
1597
- }
1598
- const b = blocks[2];
1599
- const bb = privateKey.subarray(b.position, b.position + b.length);
1600
- const block_info1 = readTag(bb, 0);
1601
- const blocks1 = _readStruct(bb, block_info1);
1602
- if (doDebug2) {
1603
- console.log(
1604
- blocks1.map((b2) => ({
1605
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1606
- l: b2.length,
1607
- p: b2.position,
1608
- buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1609
- }))
1610
- );
1611
- }
1612
- const version = f(bb, blocks1[0]);
1613
- const modulus = f(bb, blocks1[1]);
1614
- const publicExponent = f(bb, blocks1[2]);
1615
- const privateExponent = f(bb, blocks1[3]);
1616
- const prime1 = f(bb, blocks1[4]);
1617
- const prime2 = f(bb, blocks1[5]);
1618
- const exponent1 = f(bb, blocks1[6]);
1619
- const exponent2 = f(bb, blocks1[7]);
1620
- return {
1621
- version,
1622
- modulus,
1623
- publicExponent,
1624
- privateExponent,
1625
- prime1,
1626
- prime2,
1627
- exponent1,
1628
- exponent2
1629
- };
1630
- }
1631
-
1632
- // source/public_private_match.ts
1633
- function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1634
- const i = exploreCertificate(certificate);
1635
- const j = explorePrivateKey(privateKey);
1636
- const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1637
- const modulus2 = j.modulus;
1638
- if (modulus1.length != modulus2.length) {
1639
- return false;
1640
- }
1641
- return modulus1.toString("hex") === modulus2.toString("hex");
1642
- }
1643
- function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1644
- const initialBuffer = Buffer.from("Lorem Ipsum");
1645
- const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1646
- const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1647
- const finalString = decryptedBuffer.toString("utf-8");
1648
- return initialBuffer.toString("utf-8") === finalString;
1649
- }
1650
- function certificateMatchesPrivateKey(certificate, privateKey) {
1651
- const e = explorePrivateKey(privateKey);
1652
- const blockSize = e.modulus.length;
1653
- const certificatePEM = toPem(certificate, "CERTIFICATE");
1654
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1655
- }
1656
-
1657
- // source/x509/_crypto.ts
1658
- import * as x509 from "@peculiar/x509";
1659
- import { Crypto as PeculiarWebCrypto } from "@peculiar/webcrypto";
1660
- import nativeCrypto from "crypto";
1661
- import * as x5092 from "@peculiar/x509";
1662
- var doDebug3 = false;
1663
- var _crypto;
1664
- var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1665
- if (typeof window === "undefined") {
1666
- _crypto = nativeCrypto;
1667
- if (!_crypto?.subtle || ignoreCrypto) {
1668
- _crypto = new PeculiarWebCrypto();
1669
- doDebug3 && console.warn("using @peculiar/webcrypto");
1670
- } else {
1671
- doDebug3 && console.warn("using nodejs crypto (native)");
1672
- }
1673
- x509.cryptoProvider.set(_crypto);
1674
- } else {
1675
- doDebug3 && console.warn("using browser crypto (native)");
1676
- _crypto = crypto;
1677
- x509.cryptoProvider.set(crypto);
1678
- }
1679
- function getCrypto() {
1680
- return _crypto || crypto || __require("crypto");
1681
- }
1682
-
1683
- // source/x509/create_key_pair.ts
1684
- async function generateKeyPair(modulusLength = 2048) {
1685
- const crypto3 = getCrypto();
1686
- const alg = {
1687
- name: "RSASSA-PKCS1-v1_5",
1688
- hash: { name: "SHA-256" },
1689
- publicExponent: new Uint8Array([1, 0, 1]),
1690
- modulusLength
1691
- };
1692
- const keys = await crypto3.subtle.generateKey(alg, true, ["sign", "verify"]);
1693
- return keys;
1694
- }
1695
- async function generatePrivateKey(modulusLength = 2048) {
1696
- return (await generateKeyPair(modulusLength)).privateKey;
1697
- }
1698
- async function privateKeyToPEM(privateKey) {
1699
- const crypto3 = getCrypto();
1700
- const privDer = await crypto3.subtle.exportKey("pkcs8", privateKey);
1701
- const privPem = x5092.PemConverter.encode(privDer, "PRIVATE KEY");
1702
- return { privPem, privDer };
1703
- }
1704
- async function derToPrivateKey(privDer) {
1705
- const crypto3 = getCrypto();
1706
- return await crypto3.subtle.importKey(
1707
- "pkcs8",
1708
- privDer,
1709
- {
1710
- name: "RSASSA-PKCS1-v1_5",
1711
- hash: { name: "SHA-256" }
1712
- },
1713
- true,
1714
- [
1715
- "sign"
1716
- // "encrypt",
1717
- // "decrypt",
1718
- // "verify",
1719
- // "wrapKey",
1720
- // "unwrapKey",
1721
- // "deriveKey",
1722
- // "deriveBits"
1723
- ]
1724
- );
1609
+ return { extensionRequest };
1610
+ }
1611
+ throw new Error("Invalid CSR or ");
1725
1612
  }
1726
- async function pemToPrivateKey(pem) {
1727
- const privDer = x5092.PemConverter.decode(pem);
1728
- return derToPrivateKey(privDer[0]);
1613
+ function exploreCertificateSigningRequest(crl) {
1614
+ const blockInfo = readTag(crl, 0);
1615
+ const blocks = readStruct(crl, blockInfo);
1616
+ const csrInfo = readCertificationRequestInfo(crl, blocks[0]);
1617
+ return csrInfo;
1618
+ }
1619
+
1620
+ // source/make_private_key_from_pem.ts
1621
+ function makePrivateKeyFromPem(privateKeyInPem) {
1622
+ return { hidden: privateKeyInPem };
1623
+ }
1624
+
1625
+ // source/make_private_key_thumbprint.ts
1626
+ function makePrivateKeyThumbPrint(privateKey) {
1627
+ return Buffer.alloc(0);
1729
1628
  }
1730
1629
 
1731
1630
  // source/subject.ts
@@ -1810,11 +1709,180 @@ var Subject = class _Subject {
1810
1709
  return this.toStringInternal("/");
1811
1710
  }
1812
1711
  toString() {
1813
- const t = this.toStringForOPCUA();
1814
- return t ? "/" + t : t;
1712
+ const t2 = this.toStringForOPCUA();
1713
+ return t2 ? "/" + t2 : t2;
1815
1714
  }
1816
1715
  };
1817
1716
 
1717
+ // source/verify_certificate_signature.ts
1718
+ import { createVerify as createVerify2 } from "crypto";
1719
+ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1720
+ const block_info = readTag(certificateOrCrl, 0);
1721
+ const blocks = readStruct(certificateOrCrl, block_info);
1722
+ const bufferToBeSigned = certificateOrCrl.subarray(block_info.position, blocks[1].position - 2);
1723
+ const signatureAlgorithm = readAlgorithmIdentifier(certificateOrCrl, blocks[1]);
1724
+ const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
1725
+ const p = split_der(parentCertificate)[0];
1726
+ const certPem = toPem(p, "CERTIFICATE");
1727
+ const verify = createVerify2(signatureAlgorithm.identifier);
1728
+ verify.update(bufferToBeSigned);
1729
+ verify.end();
1730
+ return verify.verify(certPem, signatureValue);
1731
+ }
1732
+ function verifyCertificateSignature(certificate, parentCertificate) {
1733
+ return verifyCertificateOrClrSignature(certificate, parentCertificate);
1734
+ }
1735
+ function verifyCertificateRevocationListSignature(certificateRevocationList, parentCertificate) {
1736
+ return verifyCertificateOrClrSignature(certificateRevocationList, parentCertificate);
1737
+ }
1738
+ async function verifyCertificateChain(certificateChain) {
1739
+ for (let index = 1; index < certificateChain.length; index++) {
1740
+ const cert = certificateChain[index - 1];
1741
+ const certParent = certificateChain[index];
1742
+ const certParentInfo = exploreCertificate(certParent);
1743
+ const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1744
+ if (!keyUsage.keyCertSign) {
1745
+ return {
1746
+ status: "BadCertificateIssuerUseNotAllowed",
1747
+ reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
1748
+ };
1749
+ }
1750
+ const parentSignChild = verifyCertificateSignature(cert, certParent);
1751
+ if (!parentSignChild) {
1752
+ return {
1753
+ status: "BadCertificateInvalid",
1754
+ reason: "One of the certificate in the chain is not signing the previous certificate"
1755
+ };
1756
+ }
1757
+ const certInfo = exploreCertificate(cert);
1758
+ if (!certInfo.tbsCertificate.extensions) {
1759
+ return {
1760
+ status: "BadCertificateInvalid",
1761
+ reason: "Cannot find X409 Extension 3 in certificate"
1762
+ };
1763
+ }
1764
+ if (!certParentInfo.tbsCertificate.extensions || !certInfo.tbsCertificate.extensions.authorityKeyIdentifier) {
1765
+ return {
1766
+ status: "BadCertificateInvalid",
1767
+ reason: "Cannot find X409 Extension 3 in certificate (parent)"
1768
+ };
1769
+ }
1770
+ if (certParentInfo.tbsCertificate.extensions.subjectKeyIdentifier !== certInfo.tbsCertificate.extensions.authorityKeyIdentifier.keyIdentifier) {
1771
+ return {
1772
+ status: "BadCertificateInvalid",
1773
+ reason: "subjectKeyIdentifier authorityKeyIdentifier in child certificate do not match subjectKeyIdentifier of parent certificate"
1774
+ };
1775
+ }
1776
+ }
1777
+ return {
1778
+ status: "Good",
1779
+ reason: `certificate chain is valid(length = ${certificateChain.length})`
1780
+ };
1781
+ }
1782
+
1783
+ // source/x509/_crypto.ts
1784
+ import * as x509 from "@peculiar/x509";
1785
+ import { Crypto as PeculiarWebCrypto } from "@peculiar/webcrypto";
1786
+ import nativeCrypto from "crypto";
1787
+ import * as x5092 from "@peculiar/x509";
1788
+ var doDebug3 = false;
1789
+ var _crypto;
1790
+ var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1791
+ if (typeof window === "undefined") {
1792
+ _crypto = nativeCrypto;
1793
+ if (!_crypto?.subtle || ignoreCrypto) {
1794
+ _crypto = new PeculiarWebCrypto();
1795
+ doDebug3 && console.warn("using @peculiar/webcrypto");
1796
+ } else {
1797
+ doDebug3 && console.warn("using nodejs crypto (native)");
1798
+ }
1799
+ x509.cryptoProvider.set(_crypto);
1800
+ } else {
1801
+ doDebug3 && console.warn("using browser crypto (native)");
1802
+ _crypto = crypto;
1803
+ x509.cryptoProvider.set(crypto);
1804
+ }
1805
+ function getCrypto() {
1806
+ return _crypto || crypto || __require("crypto");
1807
+ }
1808
+
1809
+ // source/x509/create_key_pair.ts
1810
+ async function generateKeyPair(modulusLength = 2048) {
1811
+ const crypto3 = getCrypto();
1812
+ const alg = {
1813
+ name: "RSASSA-PKCS1-v1_5",
1814
+ hash: { name: "SHA-256" },
1815
+ publicExponent: new Uint8Array([1, 0, 1]),
1816
+ modulusLength
1817
+ };
1818
+ const keys = await crypto3.subtle.generateKey(alg, true, ["sign", "verify"]);
1819
+ return keys;
1820
+ }
1821
+ async function generatePrivateKey(modulusLength = 2048) {
1822
+ return (await generateKeyPair(modulusLength)).privateKey;
1823
+ }
1824
+ async function privateKeyToPEM(privateKey) {
1825
+ const crypto3 = getCrypto();
1826
+ const privDer = await crypto3.subtle.exportKey("pkcs8", privateKey);
1827
+ const privPem = x5092.PemConverter.encode(privDer, "PRIVATE KEY");
1828
+ return { privPem, privDer };
1829
+ }
1830
+ async function derToPrivateKey(privDer) {
1831
+ const crypto3 = getCrypto();
1832
+ return await crypto3.subtle.importKey(
1833
+ "pkcs8",
1834
+ privDer,
1835
+ {
1836
+ name: "RSASSA-PKCS1-v1_5",
1837
+ hash: { name: "SHA-256" }
1838
+ },
1839
+ true,
1840
+ [
1841
+ "sign"
1842
+ // "encrypt",
1843
+ // "decrypt",
1844
+ // "verify",
1845
+ // "wrapKey",
1846
+ // "unwrapKey",
1847
+ // "deriveKey",
1848
+ // "deriveBits"
1849
+ ]
1850
+ );
1851
+ }
1852
+ async function pemToPrivateKey(pem) {
1853
+ const privDer = x5092.PemConverter.decode(pem);
1854
+ return derToPrivateKey(privDer[0]);
1855
+ }
1856
+
1857
+ // source/x509/coerce_private_key.ts
1858
+ var crypto2 = getCrypto();
1859
+ var doDebug4 = false;
1860
+ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1861
+ if (typeof privateKeyInDerOrPem === "string") {
1862
+ const hidden = createPrivateKeyFromNodeJSCrypto(privateKeyInDerOrPem);
1863
+ return { hidden };
1864
+ }
1865
+ throw new Error("not implemented");
1866
+ }
1867
+ async function _coercePrivateKey(privateKey) {
1868
+ const KeyObject4 = crypto2.KeyObject;
1869
+ if (privateKey instanceof Buffer) {
1870
+ const privateKey1 = await derToPrivateKey(privateKey);
1871
+ return KeyObject4.from(privateKey1);
1872
+ } else if (typeof privateKey === "string") {
1873
+ try {
1874
+ const privateKey1 = await pemToPrivateKey(privateKey);
1875
+ return KeyObject4.from(privateKey1);
1876
+ } catch (err) {
1877
+ doDebug4 && console.log(privateKey);
1878
+ throw err;
1879
+ }
1880
+ } else if (privateKey instanceof KeyObject4) {
1881
+ return privateKey;
1882
+ }
1883
+ throw new Error("Invalid privateKey");
1884
+ }
1885
+
1818
1886
  // source/x509/_get_attributes.ts
1819
1887
  var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1820
1888
  var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
@@ -5356,11 +5424,11 @@ function compareSchema(root, inputData, inputSchema) {
5356
5424
  };
5357
5425
  }
5358
5426
  if (inputSchema.primitiveSchema && VALUE_HEX_VIEW in inputData.valueBlock) {
5359
- const asn1 = localFromBER(inputData.valueBlock.valueHexView);
5360
- if (asn1.offset === -1) {
5427
+ const asn12 = localFromBER(inputData.valueBlock.valueHexView);
5428
+ if (asn12.offset === -1) {
5361
5429
  const _result = {
5362
5430
  verified: false,
5363
- result: asn1.result
5431
+ result: asn12.result
5364
5432
  };
5365
5433
  if (inputSchema.name) {
5366
5434
  inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
@@ -5371,7 +5439,7 @@ function compareSchema(root, inputData, inputSchema) {
5371
5439
  }
5372
5440
  return _result;
5373
5441
  }
5374
- return compareSchema(root, asn1.result, inputSchema.primitiveSchema);
5442
+ return compareSchema(root, asn12.result, inputSchema.primitiveSchema);
5375
5443
  }
5376
5444
  return {
5377
5445
  verified: true,
@@ -5385,14 +5453,14 @@ function verifySchema(inputBuffer, inputSchema) {
5385
5453
  result: { error: "Wrong ASN.1 schema type" }
5386
5454
  };
5387
5455
  }
5388
- const asn1 = localFromBER(BufferSourceConverter.toUint8Array(inputBuffer));
5389
- if (asn1.offset === -1) {
5456
+ const asn12 = localFromBER(BufferSourceConverter.toUint8Array(inputBuffer));
5457
+ if (asn12.offset === -1) {
5390
5458
  return {
5391
5459
  verified: false,
5392
- result: asn1.result
5460
+ result: asn12.result
5393
5461
  };
5394
5462
  }
5395
- return compareSchema(asn1.result, asn1.result, inputSchema);
5463
+ return compareSchema(asn12.result, asn12.result, inputSchema);
5396
5464
  }
5397
5465
 
5398
5466
  // ../../node_modules/@peculiar/asn1-schema/build/es2015/enums.js
@@ -6080,70 +6148,12 @@ async function createSelfSignedCertificate({
6080
6148
  return { cert: cert.toString("pem"), der: cert };
6081
6149
  }
6082
6150
 
6083
- // source/x509/coerce_private_key.ts
6084
- var crypto2 = getCrypto();
6085
- var doDebug4 = false;
6086
- function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
6087
- if (typeof privateKeyInDerOrPem === "string") {
6088
- const hidden = createPrivateKeyFromNodeJSCrypto(privateKeyInDerOrPem);
6089
- return { hidden };
6090
- }
6091
- throw new Error("not implemented");
6092
- }
6093
- async function _coercePrivateKey(privateKey) {
6094
- const KeyObject4 = crypto2.KeyObject;
6095
- if (privateKey instanceof Buffer) {
6096
- const privateKey1 = await derToPrivateKey(privateKey);
6097
- return KeyObject4.from(privateKey1);
6098
- } else if (typeof privateKey === "string") {
6099
- try {
6100
- const privateKey1 = await pemToPrivateKey(privateKey);
6101
- return KeyObject4.from(privateKey1);
6102
- } catch (err) {
6103
- doDebug4 && console.log(privateKey);
6104
- throw err;
6105
- }
6106
- } else if (privateKey instanceof KeyObject4) {
6107
- return privateKey;
6108
- }
6109
- throw new Error("Invalid privateKey");
6110
- }
6111
-
6112
- // source/make_private_key_from_pem.ts
6113
- function makePrivateKeyFromPem(privateKeyInPem) {
6114
- return { hidden: privateKeyInPem };
6115
- }
6151
+ // source/index_web.ts
6152
+ var asn1 = { readDirectoryName, readTag, readStruct, readAlgorithmIdentifier, readSignatureValueBin };
6116
6153
 
6117
6154
  export {
6118
6155
  __dirname,
6119
- createPrivateKeyFromNodeJSCrypto,
6120
- isKeyObject,
6121
- CertificatePurpose,
6122
- TagType,
6123
- readTag,
6124
- _readStruct,
6125
- parseBitString,
6126
- _readBitString,
6127
- formatBuffer2DigitHexWithColum,
6128
- _readOctetString,
6129
- _getBlock,
6130
- _readIntegerAsByteString,
6131
- _readListOfInteger,
6132
- _readObjectIdentifier,
6133
- _readAlgorithmIdentifier,
6134
- _readECCAlgorithmIdentifier,
6135
- _readSignatureValueBin,
6136
- _readSignatureValue,
6137
- _readLongIntegerValue,
6138
- _readIntegerValue,
6139
- _readBooleanValue,
6140
- _readVersionValue,
6141
- _readValue,
6142
- compactDirectoryName,
6143
- _readDirectoryName,
6144
- _findBlockAtIndex,
6145
- _readTime,
6146
- _readExtension,
6156
+ readExtension,
6147
6157
  readTbsCertificate,
6148
6158
  exploreCertificate,
6149
6159
  split_der,
@@ -6168,6 +6178,19 @@ export {
6168
6178
  coerceCertificatePem,
6169
6179
  extractPublicKeyFromCertificateSync,
6170
6180
  extractPublicKeyFromCertificate,
6181
+ explorePrivateKey,
6182
+ publicKeyAndPrivateKeyMatches,
6183
+ certificateMatchesPrivateKey,
6184
+ createPrivateKeyFromNodeJSCrypto,
6185
+ isKeyObject,
6186
+ CertificatePurpose,
6187
+ rsaLengthPrivateKey,
6188
+ toPem2,
6189
+ coercePrivateKeyPem,
6190
+ coercePublicKeyPem,
6191
+ coerceRsaPublicKeyPem,
6192
+ rsaLengthPublicKey,
6193
+ rsaLengthRsaPublicKey,
6171
6194
  coerceCertificate,
6172
6195
  exploreCertificateInfo,
6173
6196
  makePseudoRandomBuffer,
@@ -6180,35 +6203,28 @@ export {
6180
6203
  decryptBufferWithDerivedKeys,
6181
6204
  makeMessageChunkSignatureWithDerivedKeys,
6182
6205
  verifyChunkSignatureWithDerivedKeys,
6183
- rsaLengthPrivateKey,
6184
- toPem2,
6185
- coercePrivateKeyPem,
6186
- coercePublicKeyPem,
6187
- coerceRsaPublicKeyPem,
6188
- rsaLengthPublicKey,
6189
- rsaLengthRsaPublicKey,
6190
- verifyCertificateOrClrSignature,
6191
- verifyCertificateSignature,
6192
- verifyCertificateRevocationListSignature,
6193
- verifyCertificateChain,
6206
+ exploreAsn1,
6194
6207
  readNameForCrl,
6195
6208
  exploreCertificateRevocationList,
6196
6209
  readCertificationRequestInfo,
6197
6210
  exploreCertificateSigningRequest,
6198
- explorePrivateKey,
6199
- publicKeyAndPrivateKeyMatches,
6200
- certificateMatchesPrivateKey,
6211
+ makePrivateKeyFromPem,
6212
+ makePrivateKeyThumbPrint,
6213
+ Subject,
6214
+ verifyCertificateOrClrSignature,
6215
+ verifyCertificateSignature,
6216
+ verifyCertificateRevocationListSignature,
6217
+ verifyCertificateChain,
6201
6218
  generateKeyPair,
6202
6219
  generatePrivateKey,
6203
6220
  privateKeyToPEM,
6204
6221
  derToPrivateKey,
6205
6222
  pemToPrivateKey,
6206
- Subject,
6207
- createCertificateSigningRequest,
6208
- createSelfSignedCertificate,
6209
6223
  coercePEMorDerToPrivateKey,
6210
6224
  _coercePrivateKey,
6211
- makePrivateKeyFromPem
6225
+ createCertificateSigningRequest,
6226
+ createSelfSignedCertificate,
6227
+ asn1
6212
6228
  };
6213
6229
  /*! Bundled license information:
6214
6230
 
@@ -6278,4 +6294,4 @@ asn1js/build/index.es.js:
6278
6294
  *
6279
6295
  *)
6280
6296
  */
6281
- //# sourceMappingURL=chunk-46EEAYVO.mjs.map
6297
+ //# sourceMappingURL=chunk-LHUQUHQQ.mjs.map