node-opcua-crypto 4.10.0 → 4.11.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 (44) hide show
  1. package/README.md +9 -4
  2. package/dist/{chunk-46EEAYVO.mjs → chunk-2RCYFHGG.mjs} +730 -719
  3. package/dist/chunk-2RCYFHGG.mjs.map +1 -0
  4. package/dist/chunk-C7PROBPE.mjs +14 -0
  5. package/dist/chunk-C7PROBPE.mjs.map +1 -0
  6. package/dist/{chunk-GNEWUC7X.mjs → chunk-UH5AT3JE.mjs} +9 -15
  7. package/dist/chunk-UH5AT3JE.mjs.map +1 -0
  8. package/dist/index.d.mts +3 -3
  9. package/dist/index.d.ts +3 -3
  10. package/dist/index.js +517 -565
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +7 -53
  13. package/dist/index_web-C5Oeu9mq.d.mts +503 -0
  14. package/dist/index_web-D1qc4UN2.d.ts +503 -0
  15. package/dist/source/index.d.mts +13 -3
  16. package/dist/source/index.d.ts +13 -3
  17. package/dist/source/index.js +481 -522
  18. package/dist/source/index.js.map +1 -1
  19. package/dist/source/index.mjs +7 -51
  20. package/dist/source/index_web.d.mts +4 -528
  21. package/dist/source/index_web.d.ts +4 -528
  22. package/dist/source/index_web.js +498 -515
  23. package/dist/source/index_web.js.map +1 -1
  24. package/dist/source/index_web.mjs +5 -49
  25. package/dist/source_nodejs/index.d.mts +1 -2
  26. package/dist/source_nodejs/index.d.ts +1 -2
  27. package/dist/source_nodejs/index.js +31 -38
  28. package/dist/source_nodejs/index.js.map +1 -1
  29. package/dist/source_nodejs/index.mjs +3 -5
  30. package/package.json +9 -4
  31. package/dist/chunk-46EEAYVO.mjs.map +0 -1
  32. package/dist/chunk-GNEWUC7X.mjs.map +0 -1
  33. package/dist/chunk-VI4S2NM5.mjs +0 -38
  34. package/dist/chunk-VI4S2NM5.mjs.map +0 -1
  35. package/dist/index_web.d.mts +0 -5
  36. package/dist/index_web.d.ts +0 -5
  37. package/dist/index_web.js +0 -6414
  38. package/dist/index_web.js.map +0 -1
  39. package/dist/index_web.mjs +0 -195
  40. package/dist/index_web.mjs.map +0 -1
  41. package/index.mjs +0 -1
  42. package/index_web.ts +0 -1
  43. package/web.d.ts +0 -1
  44. package/web.mjs +0 -1
@@ -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
 
@@ -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;
@@ -450,7 +432,7 @@ function _readIntegerAsByteString(buffer, block) {
450
432
  }
451
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
437
  return _readIntegerAsByteString(buffer, innerBlock);
456
438
  });
@@ -484,24 +466,24 @@ 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
472
  identifier: _readObjectIdentifier(buffer, inner_blocks[0]).name
491
473
  };
492
474
  }
493
475
  function _readECCAlgorithmIdentifier(buffer, block) {
494
- const inner_blocks = _readStruct(buffer, block);
476
+ const inner_blocks = readStruct(buffer, block);
495
477
  return {
496
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) {
482
+ function readSignatureValueBin(buffer, block) {
501
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
488
  function _readLongIntegerValue(buffer, block) {
507
489
  assert(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
@@ -582,18 +564,15 @@ function _readValue(buffer, block) {
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
567
  function _readDirectoryName(buffer, block) {
589
- const set_blocks = _readStruct(buffer, block);
568
+ const set_blocks = readStruct(buffer, block);
590
569
  const names = {};
591
570
  for (const set_block of set_blocks) {
592
571
  assert(set_block.tag === 49);
593
- const blocks = _readStruct(buffer, set_block);
572
+ const blocks = readStruct(buffer, set_block);
594
573
  assert(blocks.length === 1);
595
574
  assert(blocks[0].tag === 48);
596
- const sequenceBlock = _readStruct(buffer, blocks[0]);
575
+ const sequenceBlock = readStruct(buffer, blocks[0]);
597
576
  assert(sequenceBlock.length === 2);
598
577
  const type = _readObjectIdentifier(buffer, sequenceBlock[0]);
599
578
  names[type.name] = _readValue(buffer, sequenceBlock[1]);
@@ -611,12 +590,9 @@ function _readTime(buffer, block) {
611
590
  return _readValue(buffer, block);
612
591
  }
613
592
 
614
- // source/crypto_explore_certificate.ts
615
- import assert3 from "assert";
616
-
617
593
  // source/crypto_utils.ts
618
594
  import constants from "constants";
619
- import assert2 from "assert";
595
+ import assert3 from "assert";
620
596
  import {
621
597
  createHash,
622
598
  createSign,
@@ -631,194 +607,12 @@ var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (s
631
607
  return new Buffer(size);
632
608
  };
633
609
 
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;
811
- }
812
- setImmediate(() => {
813
- callback(err1, keyPem);
814
- });
815
- }
816
-
817
610
  // source/crypto_explore_certificate.ts
611
+ import assert2 from "assert";
818
612
  var doDebug = false;
819
613
  function _readAttributeTypeAndValue(buffer, block) {
820
- let inner_blocks = _readStruct(buffer, block);
821
- inner_blocks = _readStruct(buffer, inner_blocks[0]);
614
+ let inner_blocks = readStruct(buffer, block);
615
+ inner_blocks = readStruct(buffer, inner_blocks[0]);
822
616
  const data = {
823
617
  identifier: _readObjectIdentifier(buffer, inner_blocks[0]).name,
824
618
  value: _readValue(buffer, inner_blocks[1])
@@ -830,7 +624,7 @@ function _readAttributeTypeAndValue(buffer, block) {
830
624
  return result;
831
625
  }
832
626
  function _readRelativeDistinguishedName(buffer, block) {
833
- const inner_blocks = _readStruct(buffer, block);
627
+ const inner_blocks = readStruct(buffer, block);
834
628
  const data = inner_blocks.map((block2) => _readAttributeTypeAndValue(buffer, block2));
835
629
  const result = {};
836
630
  for (const e of data) {
@@ -842,7 +636,7 @@ function _readName(buffer, block) {
842
636
  return _readRelativeDistinguishedName(buffer, block);
843
637
  }
844
638
  function _readValidity(buffer, block) {
845
- const inner_blocks = _readStruct(buffer, block);
639
+ const inner_blocks = readStruct(buffer, block);
846
640
  return {
847
641
  notBefore: _readTime(buffer, inner_blocks[0]),
848
642
  notAfter: _readTime(buffer, inner_blocks[1])
@@ -850,27 +644,27 @@ function _readValidity(buffer, block) {
850
644
  }
851
645
  function _readAuthorityKeyIdentifier(buffer) {
852
646
  const block_info = readTag(buffer, 0);
853
- const blocks = _readStruct(buffer, block_info);
647
+ const blocks = readStruct(buffer, block_info);
854
648
  const keyIdentifier_block = _findBlockAtIndex(blocks, 0);
855
649
  const authorityCertIssuer_block = _findBlockAtIndex(blocks, 1);
856
650
  const authorityCertSerialNumber_block = _findBlockAtIndex(blocks, 2);
857
651
  function _readAuthorityCertIssuer(block) {
858
- const inner_blocks = _readStruct(buffer, block);
652
+ const inner_blocks = readStruct(buffer, block);
859
653
  const directoryName_block = _findBlockAtIndex(inner_blocks, 4);
860
654
  if (directoryName_block) {
861
- const a = _readStruct(buffer, directoryName_block);
655
+ const a = readStruct(buffer, directoryName_block);
862
656
  return _readDirectoryName(buffer, a[0]);
863
657
  } else {
864
658
  throw new Error("Invalid _readAuthorityCertIssuer");
865
659
  }
866
660
  }
867
661
  function _readAuthorityCertIssuerFingerPrint(block) {
868
- const inner_blocks = _readStruct(buffer, block);
662
+ const inner_blocks = readStruct(buffer, block);
869
663
  const directoryName_block = _findBlockAtIndex(inner_blocks, 4);
870
664
  if (!directoryName_block) {
871
665
  return "";
872
666
  }
873
- const a = _readStruct(buffer, directoryName_block);
667
+ const a = readStruct(buffer, directoryName_block);
874
668
  if (a.length < 1) {
875
669
  return "";
876
670
  }
@@ -889,7 +683,7 @@ function _readAuthorityKeyIdentifier(buffer) {
889
683
  }
890
684
  function readBasicConstraint2_5_29_19(buffer, block) {
891
685
  const block_info = readTag(buffer, 0);
892
- const inner_blocks = _readStruct(buffer, block_info).slice(0, 2);
686
+ const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
893
687
  let cA = false;
894
688
  let pathLengthConstraint = 0;
895
689
  let breakControl = 0;
@@ -921,7 +715,7 @@ function _readGeneralNames(buffer, block) {
921
715
  8: { name: "registeredID", type: "OBJECT_IDENTIFIER" },
922
716
  32: { name: "otherName", type: "AnotherName" }
923
717
  };
924
- const blocks = _readStruct(buffer, block);
718
+ const blocks = readStruct(buffer, block);
925
719
  function _readFromType(buffer2, block2, type) {
926
720
  switch (type) {
927
721
  case "IA5String":
@@ -932,16 +726,16 @@ function _readGeneralNames(buffer, block) {
932
726
  }
933
727
  const n = {};
934
728
  for (const block2 of blocks) {
935
- assert3((block2.tag & 128) === 128);
936
- const t = block2.tag & 127;
937
- const type = _data[t];
729
+ assert2((block2.tag & 128) === 128);
730
+ const t2 = block2.tag & 127;
731
+ const type = _data[t2];
938
732
  if (!type) {
939
- console.log("_readGeneralNames: INVALID TYPE => " + t + " 0x" + t.toString(16));
733
+ console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
940
734
  continue;
941
735
  }
942
- if (t == 32) {
736
+ if (t2 == 32) {
943
737
  n[type.name] = n[type.name] || [];
944
- const blocks2 = _readStruct(buffer, block2);
738
+ const blocks2 = readStruct(buffer, block2);
945
739
  const name = _readObjectIdentifier(buffer, blocks2[0]).name;
946
740
  const buf = _getBlock(buffer, blocks2[1]);
947
741
  const b = readTag(buf, 0);
@@ -992,9 +786,9 @@ function readKeyUsage(oid, buffer) {
992
786
  };
993
787
  }
994
788
  function readExtKeyUsage(oid, buffer) {
995
- assert3(oid === "2.5.29.37");
789
+ assert2(oid === "2.5.29.37");
996
790
  const block_info = readTag(buffer, 0);
997
- const inner_blocks = _readStruct(buffer, block_info);
791
+ const inner_blocks = readStruct(buffer, block_info);
998
792
  const extKeyUsage = {
999
793
  serverAuth: false,
1000
794
  clientAuth: false,
@@ -1014,15 +808,15 @@ function readExtKeyUsage(oid, buffer) {
1014
808
  }
1015
809
  function _readSubjectPublicKey(buffer) {
1016
810
  const block_info = readTag(buffer, 0);
1017
- const blocks = _readStruct(buffer, block_info);
811
+ const blocks = readStruct(buffer, block_info);
1018
812
  return {
1019
813
  modulus: buffer.subarray(blocks[0].position + 1, blocks[0].position + blocks[0].length)
1020
814
  };
1021
815
  }
1022
816
  function _readExtension(buffer, block) {
1023
- const inner_blocks = _readStruct(buffer, block);
817
+ const inner_blocks = readStruct(buffer, block);
1024
818
  if (inner_blocks.length === 3) {
1025
- assert3(inner_blocks[1].tag === 1 /* BOOLEAN */);
819
+ assert2(inner_blocks[1].tag === 1 /* BOOLEAN */);
1026
820
  inner_blocks[1] = inner_blocks[2];
1027
821
  }
1028
822
  const identifier = _readObjectIdentifier(buffer, inner_blocks[0]);
@@ -1059,9 +853,9 @@ function _readExtension(buffer, block) {
1059
853
  };
1060
854
  }
1061
855
  function _readExtensions(buffer, block) {
1062
- assert3(block.tag === 163);
1063
- let inner_blocks = _readStruct(buffer, block);
1064
- inner_blocks = _readStruct(buffer, inner_blocks[0]);
856
+ assert2(block.tag === 163);
857
+ let inner_blocks = readStruct(buffer, block);
858
+ inner_blocks = readStruct(buffer, inner_blocks[0]);
1065
859
  const extensions = inner_blocks.map((block2) => _readExtension(buffer, block2));
1066
860
  const result = {};
1067
861
  for (const e of extensions) {
@@ -1070,8 +864,8 @@ function _readExtensions(buffer, block) {
1070
864
  return result;
1071
865
  }
1072
866
  function _readSubjectPublicKeyInfo(buffer, block) {
1073
- const inner_blocks = _readStruct(buffer, block);
1074
- const algorithm = _readAlgorithmIdentifier(buffer, inner_blocks[0]);
867
+ const inner_blocks = readStruct(buffer, block);
868
+ const algorithm = readAlgorithmIdentifier(buffer, inner_blocks[0]);
1075
869
  const subjectPublicKey = _readBitString(buffer, inner_blocks[1]);
1076
870
  const data = subjectPublicKey.data;
1077
871
  const values = _readListOfInteger(data);
@@ -1084,7 +878,7 @@ function _readSubjectPublicKeyInfo(buffer, block) {
1084
878
  };
1085
879
  }
1086
880
  function _readSubjectECCPublicKeyInfo(buffer, block) {
1087
- const inner_blocks = _readStruct(buffer, block);
881
+ const inner_blocks = readStruct(buffer, block);
1088
882
  const algorithm = _readECCAlgorithmIdentifier(buffer, inner_blocks[0]);
1089
883
  const subjectPublicKey = _readBitString(buffer, inner_blocks[1]);
1090
884
  const data = subjectPublicKey.data;
@@ -1097,13 +891,13 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
1097
891
  };
1098
892
  }
1099
893
  function readTbsCertificate(buffer, block) {
1100
- const blocks = _readStruct(buffer, block);
894
+ const blocks = readStruct(buffer, block);
1101
895
  let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1102
896
  let subjectPublicKeyInfo;
1103
897
  if (blocks.length === 6) {
1104
898
  version = 1;
1105
899
  serialNumber = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, blocks[0]));
1106
- signature = _readAlgorithmIdentifier(buffer, blocks[1]);
900
+ signature = readAlgorithmIdentifier(buffer, blocks[1]);
1107
901
  issuer = _readName(buffer, blocks[2]);
1108
902
  validity = _readValidity(buffer, blocks[3]);
1109
903
  subject = _readName(buffer, blocks[4]);
@@ -1117,13 +911,13 @@ function readTbsCertificate(buffer, block) {
1117
911
  }
1118
912
  version = _readVersionValue(buffer, version_block) + 1;
1119
913
  serialNumber = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, blocks[1]));
1120
- signature = _readAlgorithmIdentifier(buffer, blocks[2]);
914
+ signature = readAlgorithmIdentifier(buffer, blocks[2]);
1121
915
  issuer = _readName(buffer, blocks[3]);
1122
916
  validity = _readValidity(buffer, blocks[4]);
1123
917
  subject = _readName(buffer, blocks[5]);
1124
918
  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;
919
+ const inner_block = readStruct(buffer, blocks[6]);
920
+ const what_type = readAlgorithmIdentifier(buffer, inner_block[0]).identifier;
1127
921
  switch (what_type) {
1128
922
  case "rsaEncryption": {
1129
923
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
@@ -1156,14 +950,14 @@ function readTbsCertificate(buffer, block) {
1156
950
  };
1157
951
  }
1158
952
  function exploreCertificate(certificate) {
1159
- assert3(certificate instanceof Buffer);
953
+ assert2(certificate instanceof Buffer);
1160
954
  if (!certificate._exploreCertificate_cache) {
1161
955
  const block_info = readTag(certificate, 0);
1162
- const blocks = _readStruct(certificate, block_info);
956
+ const blocks = readStruct(certificate, block_info);
1163
957
  certificate._exploreCertificate_cache = {
1164
958
  tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1165
- signatureAlgorithm: _readAlgorithmIdentifier(certificate, blocks[1]),
1166
- signatureValue: _readSignatureValue(certificate, blocks[2])
959
+ signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
960
+ signatureValue: readSignatureValue(certificate, blocks[2])
1167
961
  };
1168
962
  }
1169
963
  return certificate._exploreCertificate_cache;
@@ -1185,51 +979,411 @@ function combine_der(certificates) {
1185
979
  let sum = 0;
1186
980
  b.forEach((block) => {
1187
981
  const block_info = readTag(block, 0);
1188
- assert3(block_info.position + block_info.length === block.length);
982
+ assert2(block_info.position + block_info.length === block.length);
1189
983
  sum += block.length;
1190
984
  });
1191
- assert3(sum === cert.length);
985
+ assert2(sum === cert.length);
1192
986
  }
1193
987
  return Buffer.concat(certificates);
1194
988
  }
1195
989
 
1196
- // source/explore_certificate.ts
1197
- import assert4 from "assert";
1198
- function coerceCertificate(certificate) {
1199
- if (typeof certificate === "string") {
1200
- certificate = convertPEMtoDER(certificate);
990
+ // source/crypto_utils.ts
991
+ import jsrsasign from "jsrsasign";
992
+ var { hexy } = pkg_hexy;
993
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
994
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
995
+ function identifyPemType(rawKey) {
996
+ if (rawKey instanceof Buffer) {
997
+ rawKey = rawKey.toString("utf8");
1201
998
  }
1202
- assert4(certificate instanceof Buffer);
1203
- return certificate;
999
+ const match = PEM_TYPE_REGEX.exec(rawKey);
1000
+ return !match ? void 0 : match[2];
1204
1001
  }
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);
1217
- }
1218
- return data;
1002
+ function removeTrailingLF(str) {
1003
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1004
+ return tmp;
1219
1005
  }
1220
-
1221
- // source/derived_keys.ts
1222
- import assert5 from "assert";
1223
- import { createCipheriv, createDecipheriv, createHmac } from "crypto";
1224
- function HMAC_HASH(sha1or256, secret, message) {
1225
- return createHmac(sha1or256, secret).update(message).digest();
1006
+ function toPem(raw_key, pem) {
1007
+ assert3(raw_key, "expecting a key");
1008
+ assert3(typeof pem === "string");
1009
+ let pemType = identifyPemType(raw_key);
1010
+ if (pemType) {
1011
+ return raw_key instanceof Buffer ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1012
+ } else {
1013
+ pemType = pem;
1014
+ assert3(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1015
+ let b = raw_key.toString("base64");
1016
+ let str = "-----BEGIN " + pemType + "-----\n";
1017
+ while (b.length) {
1018
+ str += b.substring(0, 64) + "\n";
1019
+ b = b.substring(64);
1020
+ }
1021
+ str += "-----END " + pemType + "-----";
1022
+ return str;
1023
+ }
1226
1024
  }
1227
- function plus(buf1, buf2) {
1228
- return Buffer.concat([buf1, buf2]);
1025
+ function convertPEMtoDER(raw_key) {
1026
+ let match;
1027
+ let pemType;
1028
+ let base64str;
1029
+ const parts = [];
1030
+ PEM_REGEX.lastIndex = 0;
1031
+ while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1032
+ pemType = match[2];
1033
+ base64str = match[3];
1034
+ base64str = base64str.replace(/\r?\n/g, "");
1035
+ parts.push(Buffer.from(base64str, "base64"));
1036
+ }
1037
+ return combine_der(parts);
1038
+ }
1039
+ function hexDump(buffer, width) {
1040
+ if (!buffer) {
1041
+ return "<>";
1042
+ }
1043
+ width = width || 32;
1044
+ if (buffer.length > 1024) {
1045
+ return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1046
+ } else {
1047
+ return hexy(buffer, { width, format: "twos" });
1048
+ }
1049
+ }
1050
+ function makeMessageChunkSignature(chunk, options) {
1051
+ const signer = createSign(options.algorithm);
1052
+ signer.update(chunk);
1053
+ const signature = signer.sign(options.privateKey.hidden);
1054
+ assert3(!options.signatureLength || signature.length === options.signatureLength);
1055
+ return signature;
1056
+ }
1057
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
1058
+ const verify = createVerify(options.algorithm);
1059
+ verify.update(blockToVerify);
1060
+ return verify.verify(options.publicKey, signature);
1061
+ }
1062
+ function makeSHA1Thumbprint(buffer) {
1063
+ return createHash("sha1").update(buffer).digest();
1064
+ }
1065
+ var RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
1066
+ var RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
1067
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1068
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1069
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1070
+ return PaddingAlgorithm2;
1071
+ })(PaddingAlgorithm || {});
1072
+ assert3(4 /* RSA_PKCS1_OAEP_PADDING */ === constants.RSA_PKCS1_OAEP_PADDING);
1073
+ assert3(1 /* RSA_PKCS1_PADDING */ === constants.RSA_PKCS1_PADDING);
1074
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
1075
+ if (algorithm === void 0) {
1076
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1077
+ }
1078
+ return publicEncrypt1(
1079
+ {
1080
+ key: publicKey,
1081
+ padding: algorithm
1082
+ },
1083
+ buffer
1084
+ );
1085
+ }
1086
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
1087
+ if (algorithm === void 0) {
1088
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1089
+ }
1090
+ try {
1091
+ return privateDecrypt1(
1092
+ {
1093
+ key: privateKey.hidden,
1094
+ padding: algorithm
1095
+ },
1096
+ buffer
1097
+ );
1098
+ } catch (err) {
1099
+ return Buffer.alloc(1);
1100
+ }
1101
+ }
1102
+ var publicEncrypt = publicEncrypt_native;
1103
+ var privateDecrypt = privateDecrypt_native;
1104
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1105
+ if (paddingAlgorithm === void 0) {
1106
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1107
+ }
1108
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1109
+ padding = padding || 11;
1110
+ if (padding !== 11) throw new Error("padding should be 11");
1111
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1112
+ padding = padding || 42;
1113
+ if (padding !== 42) throw new Error("padding should be 42");
1114
+ } else {
1115
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1116
+ }
1117
+ const chunk_size = blockSize - padding;
1118
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
1119
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1120
+ for (let i = 0; i < nbBlocks; i++) {
1121
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1122
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1123
+ if (encrypted_chunk.length !== blockSize) {
1124
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1125
+ }
1126
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
1127
+ }
1128
+ return outputBuffer;
1129
+ }
1130
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1131
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1132
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1133
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1134
+ }
1135
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
1136
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1137
+ let total_length = 0;
1138
+ for (let i = 0; i < nbBlocks; i++) {
1139
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1140
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1141
+ decrypted_buf.copy(outputBuffer, total_length);
1142
+ total_length += decrypted_buf.length;
1143
+ }
1144
+ return outputBuffer.subarray(0, total_length);
1145
+ }
1146
+ function coerceCertificatePem(certificate) {
1147
+ if (certificate instanceof Buffer) {
1148
+ certificate = toPem(certificate, "CERTIFICATE");
1149
+ }
1150
+ assert3(typeof certificate === "string");
1151
+ return certificate;
1152
+ }
1153
+ function extractPublicKeyFromCertificateSync(certificate) {
1154
+ certificate = coerceCertificatePem(certificate);
1155
+ const key = jsrsasign.KEYUTIL.getKey(certificate);
1156
+ const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
1157
+ assert3(typeof publicKeyAsPem === "string");
1158
+ return publicKeyAsPem;
1159
+ }
1160
+ function extractPublicKeyFromCertificate(certificate, callback) {
1161
+ let err1 = null;
1162
+ let keyPem;
1163
+ try {
1164
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
1165
+ } catch (err) {
1166
+ err1 = err;
1167
+ }
1168
+ setImmediate(() => {
1169
+ callback(err1, keyPem);
1170
+ });
1171
+ }
1172
+
1173
+ // source/explore_private_key.ts
1174
+ function f(buffer, b) {
1175
+ return buffer.subarray(b.position + 1, b.position + b.length);
1176
+ }
1177
+ var doDebug2 = !!process.env.DEBUG;
1178
+ function explorePrivateKey(privateKey2) {
1179
+ const privateKey1 = privateKey2.hidden;
1180
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1181
+ const block_info = readTag(privateKey, 0);
1182
+ const blocks = readStruct(privateKey, block_info);
1183
+ if (blocks.length === 9) {
1184
+ const version2 = f(privateKey, blocks[0]);
1185
+ const modulus2 = f(privateKey, blocks[1]);
1186
+ const publicExponent2 = f(privateKey, blocks[2]);
1187
+ const privateExponent2 = f(privateKey, blocks[3]);
1188
+ const prime12 = f(privateKey, blocks[4]);
1189
+ const prime22 = f(privateKey, blocks[5]);
1190
+ const exponent12 = f(privateKey, blocks[6]);
1191
+ const exponent22 = f(privateKey, blocks[7]);
1192
+ return {
1193
+ version: version2,
1194
+ modulus: modulus2,
1195
+ publicExponent: publicExponent2,
1196
+ privateExponent: privateExponent2,
1197
+ prime1: prime12,
1198
+ prime2: prime22,
1199
+ exponent1: exponent12,
1200
+ exponent2: exponent22
1201
+ };
1202
+ }
1203
+ if (doDebug2) {
1204
+ console.log("-------------------- private key:");
1205
+ console.log(block_info);
1206
+ console.log(
1207
+ blocks.map((b2) => ({
1208
+ tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1209
+ l: b2.length,
1210
+ p: b2.position,
1211
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1212
+ }))
1213
+ );
1214
+ }
1215
+ const b = blocks[2];
1216
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1217
+ const block_info1 = readTag(bb, 0);
1218
+ const blocks1 = readStruct(bb, block_info1);
1219
+ if (doDebug2) {
1220
+ console.log(
1221
+ blocks1.map((b2) => ({
1222
+ tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1223
+ l: b2.length,
1224
+ p: b2.position,
1225
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1226
+ }))
1227
+ );
1228
+ }
1229
+ const version = f(bb, blocks1[0]);
1230
+ const modulus = f(bb, blocks1[1]);
1231
+ const publicExponent = f(bb, blocks1[2]);
1232
+ const privateExponent = f(bb, blocks1[3]);
1233
+ const prime1 = f(bb, blocks1[4]);
1234
+ const prime2 = f(bb, blocks1[5]);
1235
+ const exponent1 = f(bb, blocks1[6]);
1236
+ const exponent2 = f(bb, blocks1[7]);
1237
+ return {
1238
+ version,
1239
+ modulus,
1240
+ publicExponent,
1241
+ privateExponent,
1242
+ prime1,
1243
+ prime2,
1244
+ exponent1,
1245
+ exponent2
1246
+ };
1247
+ }
1248
+
1249
+ // source/public_private_match.ts
1250
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1251
+ const i = exploreCertificate(certificate);
1252
+ const j = explorePrivateKey(privateKey);
1253
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1254
+ const modulus2 = j.modulus;
1255
+ if (modulus1.length != modulus2.length) {
1256
+ return false;
1257
+ }
1258
+ return modulus1.toString("hex") === modulus2.toString("hex");
1259
+ }
1260
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1261
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1262
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1263
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1264
+ const finalString = decryptedBuffer.toString("utf-8");
1265
+ return initialBuffer.toString("utf-8") === finalString;
1266
+ }
1267
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1268
+ const e = explorePrivateKey(privateKey);
1269
+ const blockSize = e.modulus.length;
1270
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1271
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1272
+ }
1273
+
1274
+ // source/common.ts
1275
+ import __crypto from "crypto";
1276
+ var KeyObjectOrig = __crypto.KeyObject;
1277
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = __crypto;
1278
+ function isKeyObject(mayBeKeyObject) {
1279
+ if (KeyObjectOrig) {
1280
+ return mayBeKeyObject instanceof KeyObjectOrig;
1281
+ }
1282
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1283
+ }
1284
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1285
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1286
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1287
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1288
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1289
+ return CertificatePurpose2;
1290
+ })(CertificatePurpose || {});
1291
+
1292
+ // source/crypto_utils2.ts
1293
+ import assert4 from "assert";
1294
+ import jsrsasign2 from "jsrsasign";
1295
+ function rsaLengthPrivateKey(key) {
1296
+ const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
1297
+ const a = jsrsasign2.KEYUTIL.getKey(keyPem);
1298
+ return a.n.toString(16).length / 2;
1299
+ }
1300
+ function toPem2(raw_key, pem) {
1301
+ if (raw_key.hidden) {
1302
+ return toPem2(raw_key.hidden, pem);
1303
+ }
1304
+ assert4(raw_key, "expecting a key");
1305
+ assert4(typeof pem === "string");
1306
+ if (isKeyObject(raw_key)) {
1307
+ const _raw_key = raw_key;
1308
+ if (pem === "RSA PRIVATE KEY") {
1309
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs1" }).toString());
1310
+ } else if (pem === "PRIVATE KEY") {
1311
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs8" }).toString());
1312
+ } else {
1313
+ throw new Error("Unsupported case!");
1314
+ }
1315
+ }
1316
+ return toPem(raw_key, pem);
1317
+ }
1318
+ function coercePrivateKeyPem(privateKey) {
1319
+ return toPem2(privateKey, "PRIVATE KEY");
1320
+ }
1321
+ function coercePublicKeyPem(publicKey) {
1322
+ if (isKeyObject(publicKey)) {
1323
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1324
+ }
1325
+ assert4(typeof publicKey === "string");
1326
+ return publicKey;
1327
+ }
1328
+ function coerceRsaPublicKeyPem(publicKey) {
1329
+ if (isKeyObject(publicKey)) {
1330
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1331
+ }
1332
+ assert4(typeof publicKey === "string");
1333
+ return publicKey;
1334
+ }
1335
+ function rsaLengthPublicKey(key) {
1336
+ key = coercePublicKeyPem(key);
1337
+ assert4(typeof key === "string");
1338
+ const a = jsrsasign2.KEYUTIL.getKey(key);
1339
+ return a.n.toString(16).length / 2;
1340
+ }
1341
+ function rsaLengthRsaPublicKey(key) {
1342
+ key = coerceRsaPublicKeyPem(key);
1343
+ assert4(typeof key === "string");
1344
+ const a = jsrsasign2.KEYUTIL.getKey(key);
1345
+ return a.n.toString(16).length / 2;
1346
+ }
1347
+
1348
+ // source/derived_keys.ts
1349
+ import assert6 from "assert";
1350
+ import { createCipheriv, createDecipheriv, createHmac } from "crypto";
1351
+
1352
+ // source/explore_certificate.ts
1353
+ import assert5 from "assert";
1354
+ function coerceCertificate(certificate) {
1355
+ if (typeof certificate === "string") {
1356
+ certificate = convertPEMtoDER(certificate);
1357
+ }
1358
+ assert5(certificate instanceof Buffer);
1359
+ return certificate;
1360
+ }
1361
+ function exploreCertificateInfo(certificate) {
1362
+ certificate = coerceCertificate(certificate);
1363
+ const certInfo = exploreCertificate(certificate);
1364
+ const data = {
1365
+ publicKeyLength: certInfo.tbsCertificate.subjectPublicKeyInfo.keyLength,
1366
+ notBefore: certInfo.tbsCertificate.validity.notBefore,
1367
+ notAfter: certInfo.tbsCertificate.validity.notAfter,
1368
+ publicKey: certInfo.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey,
1369
+ subject: certInfo.tbsCertificate.subject
1370
+ };
1371
+ if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1372
+ throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1373
+ }
1374
+ return data;
1375
+ }
1376
+
1377
+ // source/derived_keys.ts
1378
+ function HMAC_HASH(sha1or256, secret, message) {
1379
+ return createHmac(sha1or256, secret).update(message).digest();
1380
+ }
1381
+ function plus(buf1, buf2) {
1382
+ return Buffer.concat([buf1, buf2]);
1229
1383
  }
1230
1384
  function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1231
- assert5(seed instanceof Buffer);
1232
- assert5(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1385
+ assert6(seed instanceof Buffer);
1386
+ assert6(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1233
1387
  const a = [];
1234
1388
  a[0] = seed;
1235
1389
  let index = 1;
@@ -1242,12 +1396,12 @@ function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1242
1396
  return p_hash.subarray(0, minLength);
1243
1397
  }
1244
1398
  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");
1399
+ assert6(Number.isFinite(options.signatureLength));
1400
+ assert6(Number.isFinite(options.encryptingKeyLength));
1401
+ assert6(Number.isFinite(options.encryptingBlockSize));
1402
+ assert6(typeof options.algorithm === "string");
1249
1403
  options.sha1or256 = options.sha1or256 || "SHA1";
1250
- assert5(typeof options.sha1or256 === "string");
1404
+ assert6(typeof options.sha1or256 === "string");
1251
1405
  const offset1 = options.signingKeyLength;
1252
1406
  const offset2 = offset1 + options.encryptingKeyLength;
1253
1407
  const minLength = offset2 + options.encryptingBlockSize;
@@ -1272,7 +1426,7 @@ function removePadding(buffer) {
1272
1426
  return reduceLength(buffer, nbPaddingBytes);
1273
1427
  }
1274
1428
  function verifyChunkSignature(chunk, options) {
1275
- assert5(chunk instanceof Buffer);
1429
+ assert6(chunk instanceof Buffer);
1276
1430
  let signatureLength = options.signatureLength || 0;
1277
1431
  if (signatureLength === 0) {
1278
1432
  const cert = exploreCertificateInfo(options.publicKey);
@@ -1283,16 +1437,16 @@ function verifyChunkSignature(chunk, options) {
1283
1437
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1284
1438
  }
1285
1439
  function computePaddingFooter(buffer, derivedKeys) {
1286
- assert5(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1440
+ assert6(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1287
1441
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1288
1442
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1289
1443
  padding.fill(paddingSize);
1290
1444
  return padding;
1291
1445
  }
1292
1446
  function derivedKeys_algorithm(derivedKeys) {
1293
- assert5(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1447
+ assert6(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1294
1448
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1295
- assert5(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1449
+ assert6(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1296
1450
  return algorithm;
1297
1451
  }
1298
1452
  function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
@@ -1306,153 +1460,58 @@ function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
1306
1460
  encrypted_chunks.push(cipher.final());
1307
1461
  return Buffer.concat(encrypted_chunks);
1308
1462
  }
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;
1390
- }
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);
1463
+ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1464
+ const algorithm = derivedKeys_algorithm(derivedKeys);
1465
+ const key = derivedKeys.encryptingKey;
1466
+ const initVector = derivedKeys.initializationVector;
1467
+ const cipher = createDecipheriv(algorithm, key, initVector);
1468
+ cipher.setAutoPadding(false);
1469
+ const decrypted_chunks = [];
1470
+ decrypted_chunks.push(cipher.update(buffer));
1471
+ decrypted_chunks.push(cipher.final());
1472
+ return Buffer.concat(decrypted_chunks);
1406
1473
  }
1407
- function verifyCertificateSignature(certificate, parentCertificate) {
1408
- return verifyCertificateOrClrSignature(certificate, parentCertificate);
1474
+ function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1475
+ assert6(message instanceof Buffer);
1476
+ assert6(derivedKeys.signingKey instanceof Buffer);
1477
+ assert6(typeof derivedKeys.sha1or256 === "string");
1478
+ assert6(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1479
+ const signature = createHmac(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1480
+ assert6(signature.length === derivedKeys.signatureLength);
1481
+ return signature;
1409
1482
  }
1410
- function verifyCertificateRevocationListSignature(certificateRevocationList, parentCertificate) {
1411
- return verifyCertificateOrClrSignature(certificateRevocationList, parentCertificate);
1483
+ function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
1484
+ const message = chunk.subarray(0, chunk.length - derivedKeys.signatureLength);
1485
+ const expectedSignature = chunk.subarray(chunk.length - derivedKeys.signatureLength);
1486
+ const computedSignature = makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys);
1487
+ return computedSignature.toString("hex") === expectedSignature.toString("hex");
1412
1488
  }
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
- };
1489
+
1490
+ // source/explore_asn1.ts
1491
+ function t(tag) {
1492
+ return TagType[tag];
1493
+ }
1494
+ function bi(blockInfo, depth) {
1495
+ const indent = " ".repeat(depth);
1496
+ const hl = blockInfo.position - blockInfo.start;
1497
+ 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)}`;
1498
+ }
1499
+ function exploreAsn1(buffer) {
1500
+ console.log(hexDump(buffer));
1501
+ function dump(offset, depth) {
1502
+ const blockInfo = readTag(buffer, offset);
1503
+ dumpBlock(blockInfo, depth);
1504
+ function dumpBlock(blockInfo2, depth2) {
1505
+ console.log(bi(blockInfo2, depth2));
1506
+ if (blockInfo2.tag === 48 /* SEQUENCE */ || blockInfo2.tag === 49 /* SET */ || blockInfo2.tag >= 160 /* CONTEXT_SPECIFIC0 */) {
1507
+ const blocks = readStruct(buffer, blockInfo2);
1508
+ for (const block of blocks) {
1509
+ dumpBlock(block, depth2 + 1);
1510
+ }
1511
+ }
1450
1512
  }
1451
1513
  }
1452
- return {
1453
- status: "Good",
1454
- reason: `certificate chain is valid(length = ${certificateChain.length})`
1455
- };
1514
+ dump(0, 0);
1456
1515
  }
1457
1516
 
1458
1517
  // source/explore_certificate_revocation_list.ts
@@ -1460,20 +1519,20 @@ function readNameForCrl(buffer, block) {
1460
1519
  return _readDirectoryName(buffer, block);
1461
1520
  }
1462
1521
  function _readTbsCertList(buffer, blockInfo) {
1463
- const blocks = _readStruct(buffer, blockInfo);
1522
+ const blocks = readStruct(buffer, blockInfo);
1464
1523
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1465
1524
  if (hasOptionalVersion) {
1466
1525
  const version = _readIntegerValue(buffer, blocks[0]);
1467
- const signature = _readAlgorithmIdentifier(buffer, blocks[1]);
1526
+ const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1468
1527
  const issuer = readNameForCrl(buffer, blocks[2]);
1469
1528
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[2])));
1470
1529
  const thisUpdate = _readTime(buffer, blocks[3]);
1471
1530
  const nextUpdate = _readTime(buffer, blocks[4]);
1472
1531
  const revokedCertificates = [];
1473
1532
  if (blocks[5] && blocks[5].tag < 128) {
1474
- const list = _readStruct(buffer, blocks[5]);
1533
+ const list = readStruct(buffer, blocks[5]);
1475
1534
  for (const r of list) {
1476
- const rr = _readStruct(buffer, r);
1535
+ const rr = readStruct(buffer, r);
1477
1536
  const userCertificate = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, rr[0]));
1478
1537
  const revocationDate = _readTime(buffer, rr[1]);
1479
1538
  revokedCertificates.push({
@@ -1485,16 +1544,16 @@ function _readTbsCertList(buffer, blockInfo) {
1485
1544
  const ext0 = _findBlockAtIndex(blocks, 0);
1486
1545
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1487
1546
  } else {
1488
- const signature = _readAlgorithmIdentifier(buffer, blocks[0]);
1547
+ const signature = readAlgorithmIdentifier(buffer, blocks[0]);
1489
1548
  const issuer = readNameForCrl(buffer, blocks[1]);
1490
1549
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(_getBlock(buffer, blocks[1])));
1491
1550
  const thisUpdate = _readTime(buffer, blocks[2]);
1492
1551
  const nextUpdate = _readTime(buffer, blocks[3]);
1493
1552
  const revokedCertificates = [];
1494
1553
  if (blocks[4] && blocks[4].tag < 128) {
1495
- const list = _readStruct(buffer, blocks[4]);
1554
+ const list = readStruct(buffer, blocks[4]);
1496
1555
  for (const r of list) {
1497
- const rr = _readStruct(buffer, r);
1556
+ const rr = readStruct(buffer, r);
1498
1557
  const userCertificate = formatBuffer2DigitHexWithColum(_readLongIntegerValue(buffer, rr[0]));
1499
1558
  const revocationDate = _readTime(buffer, rr[1]);
1500
1559
  revokedCertificates.push({
@@ -1508,17 +1567,17 @@ function _readTbsCertList(buffer, blockInfo) {
1508
1567
  }
1509
1568
  function exploreCertificateRevocationList(crl) {
1510
1569
  const blockInfo = readTag(crl, 0);
1511
- const blocks = _readStruct(crl, blockInfo);
1570
+ const blocks = readStruct(crl, blockInfo);
1512
1571
  const tbsCertList = _readTbsCertList(crl, blocks[0]);
1513
- const signatureAlgorithm = _readAlgorithmIdentifier(crl, blocks[1]);
1514
- const signatureValue = _readSignatureValueBin(crl, blocks[2]);
1572
+ const signatureAlgorithm = readAlgorithmIdentifier(crl, blocks[1]);
1573
+ const signatureValue = readSignatureValueBin(crl, blocks[2]);
1515
1574
  return { tbsCertList, signatureAlgorithm, signatureValue };
1516
1575
  }
1517
1576
 
1518
1577
  // source/explore_certificate_signing_request.ts
1519
1578
  function _readExtensionRequest(buffer) {
1520
1579
  const block = readTag(buffer, 0);
1521
- const inner_blocks = _readStruct(buffer, block);
1580
+ const inner_blocks = readStruct(buffer, block);
1522
1581
  const extensions = inner_blocks.map((block1) => _readExtension(buffer, block1));
1523
1582
  const result = {};
1524
1583
  for (const e of extensions) {
@@ -1528,204 +1587,39 @@ function _readExtensionRequest(buffer) {
1528
1587
  return { basicConstraints, keyUsage, subjectAltName };
1529
1588
  }
1530
1589
  function readCertificationRequestInfo(buffer, block) {
1531
- const blocks = _readStruct(buffer, block);
1590
+ const blocks = readStruct(buffer, block);
1532
1591
  if (blocks.length === 4) {
1533
1592
  const extensionRequestBlock = _findBlockAtIndex(blocks, 0);
1534
1593
  if (!extensionRequestBlock) {
1535
1594
  throw new Error("cannot find extensionRequest block");
1536
1595
  }
1537
- const blocks1 = _readStruct(buffer, extensionRequestBlock);
1538
- const blocks2 = _readStruct(buffer, blocks1[0]);
1596
+ const blocks1 = readStruct(buffer, extensionRequestBlock);
1597
+ const blocks2 = readStruct(buffer, blocks1[0]);
1539
1598
  const identifier = _readObjectIdentifier(buffer, blocks2[0]);
1540
1599
  if (identifier.name !== "extensionRequest") {
1541
1600
  throw new Error(" Cannot find extension Request in ASN1 block");
1542
1601
  }
1543
1602
  const buf = _getBlock(buffer, blocks2[1]);
1544
- 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
- );
1603
+ const extensionRequest = _readExtensionRequest(buf);
1604
+ return { extensionRequest };
1605
+ }
1606
+ throw new Error("Invalid CSR or ");
1725
1607
  }
1726
- async function pemToPrivateKey(pem) {
1727
- const privDer = x5092.PemConverter.decode(pem);
1728
- return derToPrivateKey(privDer[0]);
1608
+ function exploreCertificateSigningRequest(crl) {
1609
+ const blockInfo = readTag(crl, 0);
1610
+ const blocks = readStruct(crl, blockInfo);
1611
+ const csrInfo = readCertificationRequestInfo(crl, blocks[0]);
1612
+ return csrInfo;
1613
+ }
1614
+
1615
+ // source/make_private_key_from_pem.ts
1616
+ function makePrivateKeyFromPem(privateKeyInPem) {
1617
+ return { hidden: privateKeyInPem };
1618
+ }
1619
+
1620
+ // source/make_private_key_thumbprint.ts
1621
+ function makePrivateKeyThumbPrint(privateKey) {
1622
+ return Buffer.alloc(0);
1729
1623
  }
1730
1624
 
1731
1625
  // source/subject.ts
@@ -1810,11 +1704,180 @@ var Subject = class _Subject {
1810
1704
  return this.toStringInternal("/");
1811
1705
  }
1812
1706
  toString() {
1813
- const t = this.toStringForOPCUA();
1814
- return t ? "/" + t : t;
1707
+ const t2 = this.toStringForOPCUA();
1708
+ return t2 ? "/" + t2 : t2;
1815
1709
  }
1816
1710
  };
1817
1711
 
1712
+ // source/verify_certificate_signature.ts
1713
+ import { createVerify as createVerify2 } from "crypto";
1714
+ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1715
+ const block_info = readTag(certificateOrCrl, 0);
1716
+ const blocks = readStruct(certificateOrCrl, block_info);
1717
+ const bufferToBeSigned = certificateOrCrl.subarray(block_info.position, blocks[1].position - 2);
1718
+ const signatureAlgorithm = readAlgorithmIdentifier(certificateOrCrl, blocks[1]);
1719
+ const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
1720
+ const p = split_der(parentCertificate)[0];
1721
+ const certPem = toPem(p, "CERTIFICATE");
1722
+ const verify = createVerify2(signatureAlgorithm.identifier);
1723
+ verify.update(bufferToBeSigned);
1724
+ verify.end();
1725
+ return verify.verify(certPem, signatureValue);
1726
+ }
1727
+ function verifyCertificateSignature(certificate, parentCertificate) {
1728
+ return verifyCertificateOrClrSignature(certificate, parentCertificate);
1729
+ }
1730
+ function verifyCertificateRevocationListSignature(certificateRevocationList, parentCertificate) {
1731
+ return verifyCertificateOrClrSignature(certificateRevocationList, parentCertificate);
1732
+ }
1733
+ async function verifyCertificateChain(certificateChain) {
1734
+ for (let index = 1; index < certificateChain.length; index++) {
1735
+ const cert = certificateChain[index - 1];
1736
+ const certParent = certificateChain[index];
1737
+ const certParentInfo = exploreCertificate(certParent);
1738
+ const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1739
+ if (!keyUsage.keyCertSign) {
1740
+ return {
1741
+ status: "BadCertificateIssuerUseNotAllowed",
1742
+ reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
1743
+ };
1744
+ }
1745
+ const parentSignChild = verifyCertificateSignature(cert, certParent);
1746
+ if (!parentSignChild) {
1747
+ return {
1748
+ status: "BadCertificateInvalid",
1749
+ reason: "One of the certificate in the chain is not signing the previous certificate"
1750
+ };
1751
+ }
1752
+ const certInfo = exploreCertificate(cert);
1753
+ if (!certInfo.tbsCertificate.extensions) {
1754
+ return {
1755
+ status: "BadCertificateInvalid",
1756
+ reason: "Cannot find X409 Extension 3 in certificate"
1757
+ };
1758
+ }
1759
+ if (!certParentInfo.tbsCertificate.extensions || !certInfo.tbsCertificate.extensions.authorityKeyIdentifier) {
1760
+ return {
1761
+ status: "BadCertificateInvalid",
1762
+ reason: "Cannot find X409 Extension 3 in certificate (parent)"
1763
+ };
1764
+ }
1765
+ if (certParentInfo.tbsCertificate.extensions.subjectKeyIdentifier !== certInfo.tbsCertificate.extensions.authorityKeyIdentifier.keyIdentifier) {
1766
+ return {
1767
+ status: "BadCertificateInvalid",
1768
+ reason: "subjectKeyIdentifier authorityKeyIdentifier in child certificate do not match subjectKeyIdentifier of parent certificate"
1769
+ };
1770
+ }
1771
+ }
1772
+ return {
1773
+ status: "Good",
1774
+ reason: `certificate chain is valid(length = ${certificateChain.length})`
1775
+ };
1776
+ }
1777
+
1778
+ // source/x509/_crypto.ts
1779
+ import * as x509 from "@peculiar/x509";
1780
+ import { Crypto as PeculiarWebCrypto } from "@peculiar/webcrypto";
1781
+ import nativeCrypto from "crypto";
1782
+ import * as x5092 from "@peculiar/x509";
1783
+ var doDebug3 = false;
1784
+ var _crypto;
1785
+ var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1786
+ if (typeof window === "undefined") {
1787
+ _crypto = nativeCrypto;
1788
+ if (!_crypto?.subtle || ignoreCrypto) {
1789
+ _crypto = new PeculiarWebCrypto();
1790
+ doDebug3 && console.warn("using @peculiar/webcrypto");
1791
+ } else {
1792
+ doDebug3 && console.warn("using nodejs crypto (native)");
1793
+ }
1794
+ x509.cryptoProvider.set(_crypto);
1795
+ } else {
1796
+ doDebug3 && console.warn("using browser crypto (native)");
1797
+ _crypto = crypto;
1798
+ x509.cryptoProvider.set(crypto);
1799
+ }
1800
+ function getCrypto() {
1801
+ return _crypto || crypto || __require("crypto");
1802
+ }
1803
+
1804
+ // source/x509/create_key_pair.ts
1805
+ async function generateKeyPair(modulusLength = 2048) {
1806
+ const crypto3 = getCrypto();
1807
+ const alg = {
1808
+ name: "RSASSA-PKCS1-v1_5",
1809
+ hash: { name: "SHA-256" },
1810
+ publicExponent: new Uint8Array([1, 0, 1]),
1811
+ modulusLength
1812
+ };
1813
+ const keys = await crypto3.subtle.generateKey(alg, true, ["sign", "verify"]);
1814
+ return keys;
1815
+ }
1816
+ async function generatePrivateKey(modulusLength = 2048) {
1817
+ return (await generateKeyPair(modulusLength)).privateKey;
1818
+ }
1819
+ async function privateKeyToPEM(privateKey) {
1820
+ const crypto3 = getCrypto();
1821
+ const privDer = await crypto3.subtle.exportKey("pkcs8", privateKey);
1822
+ const privPem = x5092.PemConverter.encode(privDer, "PRIVATE KEY");
1823
+ return { privPem, privDer };
1824
+ }
1825
+ async function derToPrivateKey(privDer) {
1826
+ const crypto3 = getCrypto();
1827
+ return await crypto3.subtle.importKey(
1828
+ "pkcs8",
1829
+ privDer,
1830
+ {
1831
+ name: "RSASSA-PKCS1-v1_5",
1832
+ hash: { name: "SHA-256" }
1833
+ },
1834
+ true,
1835
+ [
1836
+ "sign"
1837
+ // "encrypt",
1838
+ // "decrypt",
1839
+ // "verify",
1840
+ // "wrapKey",
1841
+ // "unwrapKey",
1842
+ // "deriveKey",
1843
+ // "deriveBits"
1844
+ ]
1845
+ );
1846
+ }
1847
+ async function pemToPrivateKey(pem) {
1848
+ const privDer = x5092.PemConverter.decode(pem);
1849
+ return derToPrivateKey(privDer[0]);
1850
+ }
1851
+
1852
+ // source/x509/coerce_private_key.ts
1853
+ var crypto2 = getCrypto();
1854
+ var doDebug4 = false;
1855
+ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1856
+ if (typeof privateKeyInDerOrPem === "string") {
1857
+ const hidden = createPrivateKeyFromNodeJSCrypto(privateKeyInDerOrPem);
1858
+ return { hidden };
1859
+ }
1860
+ throw new Error("not implemented");
1861
+ }
1862
+ async function _coercePrivateKey(privateKey) {
1863
+ const KeyObject4 = crypto2.KeyObject;
1864
+ if (privateKey instanceof Buffer) {
1865
+ const privateKey1 = await derToPrivateKey(privateKey);
1866
+ return KeyObject4.from(privateKey1);
1867
+ } else if (typeof privateKey === "string") {
1868
+ try {
1869
+ const privateKey1 = await pemToPrivateKey(privateKey);
1870
+ return KeyObject4.from(privateKey1);
1871
+ } catch (err) {
1872
+ doDebug4 && console.log(privateKey);
1873
+ throw err;
1874
+ }
1875
+ } else if (privateKey instanceof KeyObject4) {
1876
+ return privateKey;
1877
+ }
1878
+ throw new Error("Invalid privateKey");
1879
+ }
1880
+
1818
1881
  // source/x509/_get_attributes.ts
1819
1882
  var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1820
1883
  var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
@@ -6080,69 +6143,12 @@ async function createSelfSignedCertificate({
6080
6143
  return { cert: cert.toString("pem"), der: cert };
6081
6144
  }
6082
6145
 
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
- }
6116
-
6117
6146
  export {
6118
6147
  __dirname,
6119
- createPrivateKeyFromNodeJSCrypto,
6120
- isKeyObject,
6121
- CertificatePurpose,
6122
- TagType,
6123
6148
  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,
6149
+ readStruct,
6150
+ readAlgorithmIdentifier,
6151
+ readSignatureValueBin,
6146
6152
  _readExtension,
6147
6153
  readTbsCertificate,
6148
6154
  exploreCertificate,
@@ -6168,6 +6174,19 @@ export {
6168
6174
  coerceCertificatePem,
6169
6175
  extractPublicKeyFromCertificateSync,
6170
6176
  extractPublicKeyFromCertificate,
6177
+ explorePrivateKey,
6178
+ publicKeyAndPrivateKeyMatches,
6179
+ certificateMatchesPrivateKey,
6180
+ createPrivateKeyFromNodeJSCrypto,
6181
+ isKeyObject,
6182
+ CertificatePurpose,
6183
+ rsaLengthPrivateKey,
6184
+ toPem2,
6185
+ coercePrivateKeyPem,
6186
+ coercePublicKeyPem,
6187
+ coerceRsaPublicKeyPem,
6188
+ rsaLengthPublicKey,
6189
+ rsaLengthRsaPublicKey,
6171
6190
  coerceCertificate,
6172
6191
  exploreCertificateInfo,
6173
6192
  makePseudoRandomBuffer,
@@ -6180,35 +6199,27 @@ export {
6180
6199
  decryptBufferWithDerivedKeys,
6181
6200
  makeMessageChunkSignatureWithDerivedKeys,
6182
6201
  verifyChunkSignatureWithDerivedKeys,
6183
- rsaLengthPrivateKey,
6184
- toPem2,
6185
- coercePrivateKeyPem,
6186
- coercePublicKeyPem,
6187
- coerceRsaPublicKeyPem,
6188
- rsaLengthPublicKey,
6189
- rsaLengthRsaPublicKey,
6190
- verifyCertificateOrClrSignature,
6191
- verifyCertificateSignature,
6192
- verifyCertificateRevocationListSignature,
6193
- verifyCertificateChain,
6202
+ exploreAsn1,
6194
6203
  readNameForCrl,
6195
6204
  exploreCertificateRevocationList,
6196
6205
  readCertificationRequestInfo,
6197
6206
  exploreCertificateSigningRequest,
6198
- explorePrivateKey,
6199
- publicKeyAndPrivateKeyMatches,
6200
- certificateMatchesPrivateKey,
6207
+ makePrivateKeyFromPem,
6208
+ makePrivateKeyThumbPrint,
6209
+ Subject,
6210
+ verifyCertificateOrClrSignature,
6211
+ verifyCertificateSignature,
6212
+ verifyCertificateRevocationListSignature,
6213
+ verifyCertificateChain,
6201
6214
  generateKeyPair,
6202
6215
  generatePrivateKey,
6203
6216
  privateKeyToPEM,
6204
6217
  derToPrivateKey,
6205
6218
  pemToPrivateKey,
6206
- Subject,
6207
- createCertificateSigningRequest,
6208
- createSelfSignedCertificate,
6209
6219
  coercePEMorDerToPrivateKey,
6210
6220
  _coercePrivateKey,
6211
- makePrivateKeyFromPem
6221
+ createCertificateSigningRequest,
6222
+ createSelfSignedCertificate
6212
6223
  };
6213
6224
  /*! Bundled license information:
6214
6225
 
@@ -6278,4 +6289,4 @@ asn1js/build/index.es.js:
6278
6289
  *
6279
6290
  *)
6280
6291
  */
6281
- //# sourceMappingURL=chunk-46EEAYVO.mjs.map
6292
+ //# sourceMappingURL=chunk-2RCYFHGG.mjs.map