node-opcua-crypto 4.16.1 → 4.17.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.
@@ -105,8 +105,29 @@ __export(index_web_exports, {
105
105
  });
106
106
  module.exports = __toCommonJS(index_web_exports);
107
107
 
108
+ // source/common.ts
109
+ var import_node_crypto = __toESM(require("crypto"));
110
+ var KeyObjectOrig = import_node_crypto.default.KeyObject;
111
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_node_crypto.default;
112
+ function isKeyObject(mayBeKeyObject) {
113
+ if (KeyObjectOrig) {
114
+ return mayBeKeyObject instanceof KeyObjectOrig;
115
+ }
116
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
117
+ }
118
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
119
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
120
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
121
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
122
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
123
+ return CertificatePurpose2;
124
+ })(CertificatePurpose || {});
125
+
126
+ // source/crypto_explore_certificate.ts
127
+ var import_node_assert4 = __toESM(require("assert"));
128
+
108
129
  // source/asn1.ts
109
- var import_assert = __toESM(require("assert"));
130
+ var import_node_assert = __toESM(require("assert"));
110
131
 
111
132
  // source/oid_map.ts
112
133
  var oid_map = {
@@ -442,7 +463,7 @@ var TagType = /* @__PURE__ */ ((TagType2) => {
442
463
  function readTag(buf, pos) {
443
464
  const start = pos;
444
465
  if (buf.length <= pos) {
445
- throw new Error("Invalid position : buf.length=" + buf.length + " pos =" + pos);
466
+ throw new Error(`Invalid position : buf.length=${buf.length} pos=${pos}`);
446
467
  }
447
468
  const tag = buf.readUInt8(pos);
448
469
  pos += 1;
@@ -471,7 +492,8 @@ function readStruct(buf, blockInfo) {
471
492
  return blocks;
472
493
  }
473
494
  function parseBitString(buffer, start, end, maxLength) {
474
- const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = "(" + lenBit + " bit)\n";
495
+ const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = `(${lenBit} bit)
496
+ `;
475
497
  let s = "", skip = unusedBit;
476
498
  for (let i = end - 1; i > start; --i) {
477
499
  const b = buffer.readUInt8(i);
@@ -479,12 +501,12 @@ function parseBitString(buffer, start, end, maxLength) {
479
501
  s += b >> j & 1 ? "1" : "0";
480
502
  }
481
503
  skip = 0;
482
- (0, import_assert.default)(s.length <= maxLength);
504
+ (0, import_node_assert.default)(s.length <= maxLength);
483
505
  }
484
506
  return intro + s;
485
507
  }
486
508
  function readBitString(buffer, block) {
487
- (0, import_assert.default)(block.tag === 3 /* BIT_STRING */);
509
+ (0, import_node_assert.default)(block.tag === 3 /* BIT_STRING */);
488
510
  const data = getBlock(buffer, block);
489
511
  const ignore_bits = data.readUInt8(0);
490
512
  return {
@@ -497,14 +519,14 @@ function readBitString(buffer, block) {
497
519
  function formatBuffer2DigitHexWithColum(buffer) {
498
520
  const value = [];
499
521
  for (let i = 0; i < buffer.length; i++) {
500
- value.push(("00" + buffer.readUInt8(i).toString(16)).substr(-2, 2));
522
+ value.push(`00${buffer.readUInt8(i).toString(16)}`.substr(-2, 2));
501
523
  }
502
524
  return value.join(":").toUpperCase().replace(/^(00:)*/, "");
503
525
  }
504
526
  function readOctetString(buffer, block) {
505
- (0, import_assert.default)(block.tag === 4 /* OCTET_STRING */);
527
+ (0, import_node_assert.default)(block.tag === 4 /* OCTET_STRING */);
506
528
  const tag = readTag(buffer, block.position);
507
- (0, import_assert.default)(tag.tag === 4 /* OCTET_STRING */);
529
+ (0, import_node_assert.default)(tag.tag === 4 /* OCTET_STRING */);
508
530
  const nbBytes = tag.length;
509
531
  const pos = tag.position;
510
532
  const b = buffer.subarray(pos, pos + nbBytes);
@@ -534,19 +556,19 @@ function parseOID(buffer, start, end) {
534
556
  if (!(v & 128)) {
535
557
  if (s === "") {
536
558
  const m = n < 80 ? n < 40 ? 0 : 1 : 2;
537
- s = m + "." + (n - m * 40);
559
+ s = `${m}.${n - m * 40}`;
538
560
  } else {
539
- s += "." + n.toString();
561
+ s += `.${n.toString()}`;
540
562
  }
541
563
  n = 0;
542
564
  bits = 0;
543
565
  }
544
566
  }
545
- (0, import_assert.default)(bits === 0);
567
+ (0, import_node_assert.default)(bits === 0);
546
568
  return s;
547
569
  }
548
570
  function readObjectIdentifier(buffer, block) {
549
- (0, import_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
571
+ (0, import_node_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
550
572
  const b = buffer.subarray(block.position, block.position + block.length);
551
573
  const oid = parseOID(b, 0, block.length);
552
574
  return {
@@ -574,17 +596,17 @@ function readSignatureValue(buffer, block) {
574
596
  return readSignatureValueBin(buffer, block).toString("hex");
575
597
  }
576
598
  function readLongIntegerValue(buffer, block) {
577
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
599
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
578
600
  const pos = block.position;
579
601
  const nbBytes = block.length;
580
602
  const buf = buffer.subarray(pos, pos + nbBytes);
581
603
  return buf;
582
604
  }
583
605
  function readIntegerValue(buffer, block) {
584
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
606
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
585
607
  let pos = block.position;
586
608
  const nbBytes = block.length;
587
- (0, import_assert.default)(nbBytes < 4);
609
+ (0, import_node_assert.default)(nbBytes < 4);
588
610
  let value = 0;
589
611
  for (let i = 0; i < nbBytes; i++) {
590
612
  value = value * 256 + buffer.readUInt8(pos);
@@ -593,11 +615,11 @@ function readIntegerValue(buffer, block) {
593
615
  return value;
594
616
  }
595
617
  function readBooleanValue(buffer, block) {
596
- (0, import_assert.default)(block.tag === 1 /* BOOLEAN */, "expecting a BOOLEAN tag. got " + TagType[block.tag]);
618
+ (0, import_node_assert.default)(block.tag === 1 /* BOOLEAN */, `expecting a BOOLEAN tag. got ${TagType[block.tag]}`);
597
619
  const pos = block.position;
598
620
  const nbBytes = block.length;
599
- (0, import_assert.default)(nbBytes < 4);
600
- const value = buffer.readUInt8(pos) ? true : false;
621
+ (0, import_node_assert.default)(nbBytes < 4);
622
+ const value = !!buffer.readUInt8(pos);
601
623
  return value;
602
624
  }
603
625
  function readVersionValue(buffer, block) {
@@ -649,7 +671,7 @@ function readValue(buffer, block) {
649
671
  case 24 /* GeneralizedTime */:
650
672
  return convertGeneralizedTime(getBlock(buffer, block).toString("ascii"));
651
673
  default:
652
- throw new Error("Invalid tag 0x" + block.tag.toString(16));
674
+ throw new Error(`Invalid tag 0x${block.tag.toString(16)}`);
653
675
  }
654
676
  }
655
677
  function findBlockAtIndex(blocks, index) {
@@ -664,31 +686,229 @@ function readTime(buffer, block) {
664
686
  }
665
687
 
666
688
  // source/crypto_utils.ts
667
- var import_constants = __toESM(require("constants"));
668
- var import_assert4 = __toESM(require("assert"));
669
- var import_crypto = require("crypto");
670
- var import_hexy = __toESM(require("hexy"));
689
+ var import_node_assert2 = __toESM(require("assert"));
690
+ var import_node_constants = __toESM(require("constants"));
691
+ var import_node_crypto2 = require("crypto");
692
+ var import_jsrsasign = __toESM(require("jsrsasign"));
671
693
 
672
694
  // source/buffer_utils.ts
673
695
  var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (size) => {
674
696
  return new Buffer(size);
675
697
  };
676
698
 
677
- // source/crypto_explore_certificate.ts
678
- var import_assert3 = __toESM(require("assert"));
699
+ // source/hexy.ts
700
+ function hexy(buffer, { width, format } = {}) {
701
+ width = width || 80;
702
+ if (format === "twos") {
703
+ width = 26 * 3;
704
+ }
705
+ const regex = new RegExp(`.{1,${width}}`, "g");
706
+ const regexTwos = new RegExp(`.{1,${2}}`, "g");
707
+ let fullHex = buffer.toString("hex");
708
+ if (format === "twos") {
709
+ fullHex = fullHex.match(regexTwos)?.join(" ") || "";
710
+ }
711
+ return fullHex.match(regex)?.join("\n") || "";
712
+ }
713
+
714
+ // source/crypto_utils.ts
715
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
716
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
717
+ function identifyPemType(rawKey) {
718
+ if (Buffer.isBuffer(rawKey)) {
719
+ rawKey = rawKey.toString("utf8");
720
+ }
721
+ const match = PEM_TYPE_REGEX.exec(rawKey);
722
+ return !match ? void 0 : match[2];
723
+ }
724
+ function removeTrailingLF(str) {
725
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
726
+ return tmp;
727
+ }
728
+ function toPem(raw_key, pem) {
729
+ (0, import_node_assert2.default)(raw_key, "expecting a key");
730
+ (0, import_node_assert2.default)(typeof pem === "string");
731
+ let pemType = identifyPemType(raw_key);
732
+ if (pemType) {
733
+ return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
734
+ } else {
735
+ pemType = pem;
736
+ (0, import_node_assert2.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
737
+ let b = raw_key.toString("base64");
738
+ let str = `-----BEGIN ${pemType}-----
739
+ `;
740
+ while (b.length) {
741
+ str += `${b.substring(0, 64)}
742
+ `;
743
+ b = b.substring(64);
744
+ }
745
+ str += `-----END ${pemType}-----`;
746
+ return str;
747
+ }
748
+ }
749
+ function convertPEMtoDER(raw_key) {
750
+ let match;
751
+ let _pemType;
752
+ let base64str;
753
+ const parts = [];
754
+ PEM_REGEX.lastIndex = 0;
755
+ match = PEM_REGEX.exec(raw_key);
756
+ while (match !== null) {
757
+ _pemType = match[2];
758
+ base64str = match[3];
759
+ base64str = base64str.replace(/\r?\n/g, "");
760
+ parts.push(Buffer.from(base64str, "base64"));
761
+ match = PEM_REGEX.exec(raw_key);
762
+ }
763
+ return combine_der(parts);
764
+ }
765
+ function hexDump(buffer, width) {
766
+ if (!buffer) {
767
+ return "<>";
768
+ }
769
+ width = width || 32;
770
+ if (buffer.length > 1024) {
771
+ return `${hexy(buffer.subarray(0, 1024), { width, format: "twos" })}
772
+ .... ( ${buffer.length})`;
773
+ } else {
774
+ return hexy(buffer, { width, format: "twos" });
775
+ }
776
+ }
777
+ function makeMessageChunkSignature(chunk, options) {
778
+ const signer = (0, import_node_crypto2.createSign)(options.algorithm);
779
+ signer.update(chunk);
780
+ const signature = signer.sign(options.privateKey.hidden);
781
+ (0, import_node_assert2.default)(!options.signatureLength || signature.length === options.signatureLength);
782
+ return signature;
783
+ }
784
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
785
+ const verify = (0, import_node_crypto2.createVerify)(options.algorithm);
786
+ verify.update(blockToVerify);
787
+ return verify.verify(options.publicKey, signature);
788
+ }
789
+ function makeSHA1Thumbprint(buffer) {
790
+ return (0, import_node_crypto2.createHash)("sha1").update(buffer).digest();
791
+ }
792
+ var RSA_PKCS1_OAEP_PADDING = import_node_constants.default.RSA_PKCS1_OAEP_PADDING;
793
+ var RSA_PKCS1_PADDING = import_node_constants.default.RSA_PKCS1_PADDING;
794
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
795
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
796
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
797
+ return PaddingAlgorithm2;
798
+ })(PaddingAlgorithm || {});
799
+ (0, import_node_assert2.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_node_constants.default.RSA_PKCS1_OAEP_PADDING);
800
+ (0, import_node_assert2.default)(1 /* RSA_PKCS1_PADDING */ === import_node_constants.default.RSA_PKCS1_PADDING);
801
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
802
+ if (algorithm === void 0) {
803
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
804
+ }
805
+ return (0, import_node_crypto2.publicEncrypt)(
806
+ {
807
+ key: publicKey,
808
+ padding: algorithm
809
+ },
810
+ buffer
811
+ );
812
+ }
813
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
814
+ if (algorithm === void 0) {
815
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
816
+ }
817
+ try {
818
+ return (0, import_node_crypto2.privateDecrypt)(
819
+ {
820
+ key: privateKey.hidden,
821
+ padding: algorithm
822
+ },
823
+ buffer
824
+ );
825
+ } catch (_err) {
826
+ return Buffer.alloc(1);
827
+ }
828
+ }
829
+ var publicEncrypt = publicEncrypt_native;
830
+ var privateDecrypt = privateDecrypt_native;
831
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
832
+ if (paddingAlgorithm === void 0) {
833
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
834
+ }
835
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
836
+ padding = padding || 11;
837
+ if (padding !== 11) throw new Error("padding should be 11");
838
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
839
+ padding = padding || 42;
840
+ if (padding !== 42) throw new Error("padding should be 42");
841
+ } else {
842
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
843
+ }
844
+ const chunk_size = blockSize - padding;
845
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
846
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
847
+ for (let i = 0; i < nbBlocks; i++) {
848
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
849
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
850
+ if (encrypted_chunk.length !== blockSize) {
851
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
852
+ }
853
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
854
+ }
855
+ return outputBuffer;
856
+ }
857
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
858
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
859
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
860
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
861
+ }
862
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
863
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
864
+ let total_length = 0;
865
+ for (let i = 0; i < nbBlocks; i++) {
866
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
867
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
868
+ decrypted_buf.copy(outputBuffer, total_length);
869
+ total_length += decrypted_buf.length;
870
+ }
871
+ return outputBuffer.subarray(0, total_length);
872
+ }
873
+ function coerceCertificatePem(certificate) {
874
+ if (Buffer.isBuffer(certificate)) {
875
+ certificate = toPem(certificate, "CERTIFICATE");
876
+ }
877
+ (0, import_node_assert2.default)(typeof certificate === "string");
878
+ return certificate;
879
+ }
880
+ function extractPublicKeyFromCertificateSync(certificate) {
881
+ certificate = coerceCertificatePem(certificate);
882
+ const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
883
+ const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
884
+ (0, import_node_assert2.default)(typeof publicKeyAsPem === "string");
885
+ return publicKeyAsPem;
886
+ }
887
+ function extractPublicKeyFromCertificate(certificate, callback) {
888
+ let err1 = null;
889
+ let keyPem;
890
+ try {
891
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
892
+ } catch (err) {
893
+ err1 = err;
894
+ }
895
+ setImmediate(() => {
896
+ callback(err1, keyPem);
897
+ });
898
+ }
679
899
 
680
900
  // source/directory_name.ts
681
- var import_assert2 = __toESM(require("assert"));
901
+ var import_node_assert3 = __toESM(require("assert"));
682
902
  function readDirectoryName(buffer, block) {
683
903
  const set_blocks = readStruct(buffer, block);
684
904
  const names = {};
685
905
  for (const set_block of set_blocks) {
686
- (0, import_assert2.default)(set_block.tag === 49);
906
+ (0, import_node_assert3.default)(set_block.tag === 49);
687
907
  const blocks = readStruct(buffer, set_block);
688
- (0, import_assert2.default)(blocks.length === 1);
689
- (0, import_assert2.default)(blocks[0].tag === 48);
908
+ (0, import_node_assert3.default)(blocks.length === 1);
909
+ (0, import_node_assert3.default)(blocks[0].tag === 48);
690
910
  const sequenceBlock = readStruct(buffer, blocks[0]);
691
- (0, import_assert2.default)(sequenceBlock.length === 2);
911
+ (0, import_node_assert3.default)(sequenceBlock.length === 2);
692
912
  const type = readObjectIdentifier(buffer, sequenceBlock[0]);
693
913
  names[type.name] = readValue(buffer, sequenceBlock[1]);
694
914
  }
@@ -768,7 +988,7 @@ function _readAuthorityKeyIdentifier(buffer) {
768
988
  // can be null for self-signed certf
769
989
  };
770
990
  }
771
- function readBasicConstraint2_5_29_19(buffer, block) {
991
+ function readBasicConstraint2_5_29_19(buffer, _block) {
772
992
  const block_info = readTag(buffer, 0);
773
993
  const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
774
994
  let cA = false;
@@ -813,14 +1033,14 @@ function _readGeneralNames(buffer, block) {
813
1033
  }
814
1034
  const n = {};
815
1035
  for (const block2 of blocks) {
816
- (0, import_assert3.default)((block2.tag & 128) === 128);
1036
+ (0, import_node_assert4.default)((block2.tag & 128) === 128);
817
1037
  const t2 = block2.tag & 127;
818
1038
  const type = _data[t2];
819
1039
  if (!type) {
820
- console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
1040
+ console.log(`_readGeneralNames: INVALID TYPE => ${t2} 0x${t2.toString(16)}`);
821
1041
  continue;
822
1042
  }
823
- if (t2 == 32) {
1043
+ if (t2 === 32) {
824
1044
  n[type.name] = n[type.name] || [];
825
1045
  const blocks2 = readStruct(buffer, block2);
826
1046
  const name = readObjectIdentifier(buffer, blocks2[0]).name;
@@ -843,7 +1063,7 @@ function _readSubjectAltNames(buffer) {
843
1063
  const block_info = readTag(buffer, 0);
844
1064
  return _readGeneralNames(buffer, block_info);
845
1065
  }
846
- function readKeyUsage(oid, buffer) {
1066
+ function readKeyUsage(_oid, buffer) {
847
1067
  const block_info = readTag(buffer, 0);
848
1068
  let b2 = 0;
849
1069
  let b3 = 0;
@@ -873,7 +1093,7 @@ function readKeyUsage(oid, buffer) {
873
1093
  };
874
1094
  }
875
1095
  function readExtKeyUsage(oid, buffer) {
876
- (0, import_assert3.default)(oid === "2.5.29.37");
1096
+ (0, import_node_assert4.default)(oid === "2.5.29.37");
877
1097
  const block_info = readTag(buffer, 0);
878
1098
  const inner_blocks = readStruct(buffer, block_info);
879
1099
  const extKeyUsage = {
@@ -903,7 +1123,7 @@ function _readSubjectPublicKey(buffer) {
903
1123
  function readExtension(buffer, block) {
904
1124
  const inner_blocks = readStruct(buffer, block);
905
1125
  if (inner_blocks.length === 3) {
906
- (0, import_assert3.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
1126
+ (0, import_node_assert4.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
907
1127
  inner_blocks[1] = inner_blocks[2];
908
1128
  }
909
1129
  const identifier = readObjectIdentifier(buffer, inner_blocks[0]);
@@ -923,7 +1143,7 @@ function readExtension(buffer, block) {
923
1143
  value = readBasicConstraint2_5_29_19(buf, inner_blocks[1]);
924
1144
  break;
925
1145
  case "certExtension":
926
- value = "basicConstraints ( not implemented yet) " + buf.toString("hex");
1146
+ value = `basicConstraints ( not implemented yet) ${buf.toString("hex")}`;
927
1147
  break;
928
1148
  case "extKeyUsage":
929
1149
  value = readExtKeyUsage(identifier.oid, buf);
@@ -932,7 +1152,7 @@ function readExtension(buffer, block) {
932
1152
  value = readKeyUsage(identifier.oid, buf);
933
1153
  break;
934
1154
  default:
935
- value = "Unknown " + identifier.name + buf.toString("hex");
1155
+ value = `Unknown ${identifier.name}${buf.toString("hex")}`;
936
1156
  }
937
1157
  return {
938
1158
  identifier,
@@ -940,7 +1160,7 @@ function readExtension(buffer, block) {
940
1160
  };
941
1161
  }
942
1162
  function _readExtensions(buffer, block) {
943
- (0, import_assert3.default)(block.tag === 163);
1163
+ (0, import_node_assert4.default)(block.tag === 163);
944
1164
  let inner_blocks = readStruct(buffer, block);
945
1165
  inner_blocks = readStruct(buffer, inner_blocks[0]);
946
1166
  const extensions = inner_blocks.map((block2) => readExtension(buffer, block2));
@@ -979,10 +1199,17 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
979
1199
  }
980
1200
  function readTbsCertificate(buffer, block) {
981
1201
  const blocks = readStruct(buffer, block);
982
- let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1202
+ let _version;
1203
+ let serialNumber;
1204
+ let signature;
1205
+ let issuer;
1206
+ let validity;
1207
+ let subject;
1208
+ let subjectFingerPrint;
1209
+ let extensions;
983
1210
  let subjectPublicKeyInfo;
984
1211
  if (blocks.length === 6) {
985
- version = 1;
1212
+ _version = 1;
986
1213
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[0]));
987
1214
  signature = readAlgorithmIdentifier(buffer, blocks[1]);
988
1215
  issuer = _readName(buffer, blocks[2]);
@@ -996,7 +1223,7 @@ function readTbsCertificate(buffer, block) {
996
1223
  if (!version_block) {
997
1224
  throw new Error("cannot find version block");
998
1225
  }
999
- version = readVersionValue(buffer, version_block) + 1;
1226
+ _version = readVersionValue(buffer, version_block) + 1;
1000
1227
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[1]));
1001
1228
  signature = readAlgorithmIdentifier(buffer, blocks[2]);
1002
1229
  issuer = _readName(buffer, blocks[3]);
@@ -1009,375 +1236,74 @@ function readTbsCertificate(buffer, block) {
1009
1236
  case "rsaEncryption": {
1010
1237
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
1011
1238
  break;
1012
- }
1013
- case "ecPublicKey":
1014
- default: {
1015
- subjectPublicKeyInfo = _readSubjectECCPublicKeyInfo(buffer, blocks[6]);
1016
- break;
1017
- }
1018
- }
1019
- const extensionBlock = findBlockAtIndex(blocks, 3);
1020
- if (!extensionBlock) {
1021
- doDebug && console.log("X509 certificate is invalid : cannot find extension block version =" + version_block);
1022
- extensions = null;
1023
- } else {
1024
- extensions = _readExtensions(buffer, extensionBlock);
1025
- }
1026
- }
1027
- return {
1028
- version,
1029
- serialNumber,
1030
- signature,
1031
- issuer,
1032
- validity,
1033
- subject,
1034
- subjectFingerPrint,
1035
- subjectPublicKeyInfo,
1036
- extensions
1037
- };
1038
- }
1039
- function exploreCertificate(certificate) {
1040
- (0, import_assert3.default)(Buffer.isBuffer(certificate));
1041
- if (!certificate._exploreCertificate_cache) {
1042
- const block_info = readTag(certificate, 0);
1043
- const blocks = readStruct(certificate, block_info);
1044
- certificate._exploreCertificate_cache = {
1045
- tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1046
- signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1047
- signatureValue: readSignatureValue(certificate, blocks[2])
1048
- };
1049
- }
1050
- return certificate._exploreCertificate_cache;
1051
- }
1052
- function split_der(certificateChain) {
1053
- const certificate_chain = [];
1054
- do {
1055
- const block_info = readTag(certificateChain, 0);
1056
- const length = block_info.position + block_info.length;
1057
- const der_certificate = certificateChain.subarray(0, length);
1058
- certificate_chain.push(der_certificate);
1059
- certificateChain = certificateChain.subarray(length);
1060
- } while (certificateChain.length > 0);
1061
- return certificate_chain;
1062
- }
1063
- function combine_der(certificates) {
1064
- for (const cert of certificates) {
1065
- const b = split_der(cert);
1066
- let sum = 0;
1067
- b.forEach((block) => {
1068
- const block_info = readTag(block, 0);
1069
- (0, import_assert3.default)(block_info.position + block_info.length === block.length);
1070
- sum += block.length;
1071
- });
1072
- (0, import_assert3.default)(sum === cert.length);
1073
- }
1074
- return Buffer.concat(certificates);
1075
- }
1076
-
1077
- // source/crypto_utils.ts
1078
- var import_jsrsasign = __toESM(require("jsrsasign"));
1079
- var { hexy } = import_hexy.default;
1080
- var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
1081
- var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
1082
- function identifyPemType(rawKey) {
1083
- if (Buffer.isBuffer(rawKey)) {
1084
- rawKey = rawKey.toString("utf8");
1085
- }
1086
- const match = PEM_TYPE_REGEX.exec(rawKey);
1087
- return !match ? void 0 : match[2];
1088
- }
1089
- function removeTrailingLF(str) {
1090
- const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1091
- return tmp;
1092
- }
1093
- function toPem(raw_key, pem) {
1094
- (0, import_assert4.default)(raw_key, "expecting a key");
1095
- (0, import_assert4.default)(typeof pem === "string");
1096
- let pemType = identifyPemType(raw_key);
1097
- if (pemType) {
1098
- return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1099
- } else {
1100
- pemType = pem;
1101
- (0, import_assert4.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1102
- let b = raw_key.toString("base64");
1103
- let str = "-----BEGIN " + pemType + "-----\n";
1104
- while (b.length) {
1105
- str += b.substring(0, 64) + "\n";
1106
- b = b.substring(64);
1107
- }
1108
- str += "-----END " + pemType + "-----";
1109
- return str;
1110
- }
1111
- }
1112
- function convertPEMtoDER(raw_key) {
1113
- let match;
1114
- let pemType;
1115
- let base64str;
1116
- const parts = [];
1117
- PEM_REGEX.lastIndex = 0;
1118
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1119
- pemType = match[2];
1120
- base64str = match[3];
1121
- base64str = base64str.replace(/\r?\n/g, "");
1122
- parts.push(Buffer.from(base64str, "base64"));
1123
- }
1124
- return combine_der(parts);
1125
- }
1126
- function hexDump(buffer, width) {
1127
- if (!buffer) {
1128
- return "<>";
1129
- }
1130
- width = width || 32;
1131
- if (buffer.length > 1024) {
1132
- return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1133
- } else {
1134
- return hexy(buffer, { width, format: "twos" });
1135
- }
1136
- }
1137
- function makeMessageChunkSignature(chunk, options) {
1138
- const signer = (0, import_crypto.createSign)(options.algorithm);
1139
- signer.update(chunk);
1140
- const signature = signer.sign(options.privateKey.hidden);
1141
- (0, import_assert4.default)(!options.signatureLength || signature.length === options.signatureLength);
1142
- return signature;
1143
- }
1144
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
1145
- const verify = (0, import_crypto.createVerify)(options.algorithm);
1146
- verify.update(blockToVerify);
1147
- return verify.verify(options.publicKey, signature);
1148
- }
1149
- function makeSHA1Thumbprint(buffer) {
1150
- return (0, import_crypto.createHash)("sha1").update(buffer).digest();
1151
- }
1152
- var RSA_PKCS1_OAEP_PADDING = import_constants.default.RSA_PKCS1_OAEP_PADDING;
1153
- var RSA_PKCS1_PADDING = import_constants.default.RSA_PKCS1_PADDING;
1154
- var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1155
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1156
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1157
- return PaddingAlgorithm2;
1158
- })(PaddingAlgorithm || {});
1159
- (0, import_assert4.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_constants.default.RSA_PKCS1_OAEP_PADDING);
1160
- (0, import_assert4.default)(1 /* RSA_PKCS1_PADDING */ === import_constants.default.RSA_PKCS1_PADDING);
1161
- function publicEncrypt_native(buffer, publicKey, algorithm) {
1162
- if (algorithm === void 0) {
1163
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1164
- }
1165
- return (0, import_crypto.publicEncrypt)(
1166
- {
1167
- key: publicKey,
1168
- padding: algorithm
1169
- },
1170
- buffer
1171
- );
1172
- }
1173
- function privateDecrypt_native(buffer, privateKey, algorithm) {
1174
- if (algorithm === void 0) {
1175
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1176
- }
1177
- try {
1178
- return (0, import_crypto.privateDecrypt)(
1179
- {
1180
- key: privateKey.hidden,
1181
- padding: algorithm
1182
- },
1183
- buffer
1184
- );
1185
- } catch (err) {
1186
- return Buffer.alloc(1);
1187
- }
1188
- }
1189
- var publicEncrypt = publicEncrypt_native;
1190
- var privateDecrypt = privateDecrypt_native;
1191
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1192
- if (paddingAlgorithm === void 0) {
1193
- paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1194
- }
1195
- if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1196
- padding = padding || 11;
1197
- if (padding !== 11) throw new Error("padding should be 11");
1198
- } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1199
- padding = padding || 42;
1200
- if (padding !== 42) throw new Error("padding should be 42");
1201
- } else {
1202
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1203
- }
1204
- const chunk_size = blockSize - padding;
1205
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
1206
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1207
- for (let i = 0; i < nbBlocks; i++) {
1208
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1209
- const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1210
- if (encrypted_chunk.length !== blockSize) {
1211
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1212
- }
1213
- encrypted_chunk.copy(outputBuffer, i * blockSize);
1214
- }
1215
- return outputBuffer;
1216
- }
1217
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1218
- paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1219
- if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1220
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1221
- }
1222
- const nbBlocks = Math.ceil(buffer.length / blockSize);
1223
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1224
- let total_length = 0;
1225
- for (let i = 0; i < nbBlocks; i++) {
1226
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1227
- const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1228
- decrypted_buf.copy(outputBuffer, total_length);
1229
- total_length += decrypted_buf.length;
1230
- }
1231
- return outputBuffer.subarray(0, total_length);
1232
- }
1233
- function coerceCertificatePem(certificate) {
1234
- if (Buffer.isBuffer(certificate)) {
1235
- certificate = toPem(certificate, "CERTIFICATE");
1236
- }
1237
- (0, import_assert4.default)(typeof certificate === "string");
1238
- return certificate;
1239
- }
1240
- function extractPublicKeyFromCertificateSync(certificate) {
1241
- certificate = coerceCertificatePem(certificate);
1242
- const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
1243
- const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
1244
- (0, import_assert4.default)(typeof publicKeyAsPem === "string");
1245
- return publicKeyAsPem;
1246
- }
1247
- function extractPublicKeyFromCertificate(certificate, callback) {
1248
- let err1 = null;
1249
- let keyPem;
1250
- try {
1251
- keyPem = extractPublicKeyFromCertificateSync(certificate);
1252
- } catch (err) {
1253
- err1 = err;
1254
- }
1255
- setImmediate(() => {
1256
- callback(err1, keyPem);
1257
- });
1258
- }
1259
-
1260
- // source/explore_private_key.ts
1261
- function f(buffer, b) {
1262
- return buffer.subarray(b.position + 1, b.position + b.length);
1263
- }
1264
- var doDebug2 = !!process.env.DEBUG;
1265
- function explorePrivateKey(privateKey2) {
1266
- const privateKey1 = privateKey2.hidden;
1267
- const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1268
- const block_info = readTag(privateKey, 0);
1269
- const blocks = readStruct(privateKey, block_info);
1270
- if (blocks.length === 9) {
1271
- const version2 = f(privateKey, blocks[0]);
1272
- const modulus2 = f(privateKey, blocks[1]);
1273
- const publicExponent2 = f(privateKey, blocks[2]);
1274
- const privateExponent2 = f(privateKey, blocks[3]);
1275
- const prime12 = f(privateKey, blocks[4]);
1276
- const prime22 = f(privateKey, blocks[5]);
1277
- const exponent12 = f(privateKey, blocks[6]);
1278
- const exponent22 = f(privateKey, blocks[7]);
1279
- return {
1280
- version: version2,
1281
- modulus: modulus2,
1282
- publicExponent: publicExponent2,
1283
- privateExponent: privateExponent2,
1284
- prime1: prime12,
1285
- prime2: prime22,
1286
- exponent1: exponent12,
1287
- exponent2: exponent22
1288
- };
1289
- }
1290
- if (doDebug2) {
1291
- console.log("-------------------- private key:");
1292
- console.log(block_info);
1293
- console.log(
1294
- blocks.map((b2) => ({
1295
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1296
- l: b2.length,
1297
- p: b2.position,
1298
- buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1299
- }))
1300
- );
1301
- }
1302
- const b = blocks[2];
1303
- const bb = privateKey.subarray(b.position, b.position + b.length);
1304
- const block_info1 = readTag(bb, 0);
1305
- const blocks1 = readStruct(bb, block_info1);
1306
- if (doDebug2) {
1307
- console.log(
1308
- blocks1.map((b2) => ({
1309
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1310
- l: b2.length,
1311
- p: b2.position,
1312
- buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1313
- }))
1314
- );
1239
+ }
1240
+ default: {
1241
+ (0, import_node_assert4.default)(what_type === "ecPublicKey");
1242
+ subjectPublicKeyInfo = _readSubjectECCPublicKeyInfo(buffer, blocks[6]);
1243
+ break;
1244
+ }
1245
+ }
1246
+ const extensionBlock = findBlockAtIndex(blocks, 3);
1247
+ if (!extensionBlock) {
1248
+ doDebug && console.log(`X509 certificate is invalid : cannot find extension block version = ${version_block}`);
1249
+ extensions = null;
1250
+ } else {
1251
+ extensions = _readExtensions(buffer, extensionBlock);
1252
+ }
1315
1253
  }
1316
- const version = f(bb, blocks1[0]);
1317
- const modulus = f(bb, blocks1[1]);
1318
- const publicExponent = f(bb, blocks1[2]);
1319
- const privateExponent = f(bb, blocks1[3]);
1320
- const prime1 = f(bb, blocks1[4]);
1321
- const prime2 = f(bb, blocks1[5]);
1322
- const exponent1 = f(bb, blocks1[6]);
1323
- const exponent2 = f(bb, blocks1[7]);
1324
1254
  return {
1325
- version,
1326
- modulus,
1327
- publicExponent,
1328
- privateExponent,
1329
- prime1,
1330
- prime2,
1331
- exponent1,
1332
- exponent2
1255
+ version: _version,
1256
+ serialNumber,
1257
+ signature,
1258
+ issuer,
1259
+ validity,
1260
+ subject,
1261
+ subjectFingerPrint,
1262
+ subjectPublicKeyInfo,
1263
+ extensions
1333
1264
  };
1334
1265
  }
1335
-
1336
- // source/public_private_match.ts
1337
- function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1338
- const i = exploreCertificate(certificate);
1339
- const j = explorePrivateKey(privateKey);
1340
- const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1341
- const modulus2 = j.modulus;
1342
- if (modulus1.length != modulus2.length) {
1343
- return false;
1266
+ function exploreCertificate(certificate) {
1267
+ (0, import_node_assert4.default)(Buffer.isBuffer(certificate));
1268
+ const certificate_priv = certificate;
1269
+ if (!certificate_priv._exploreCertificate_cache) {
1270
+ const block_info = readTag(certificate, 0);
1271
+ const blocks = readStruct(certificate, block_info);
1272
+ certificate_priv._exploreCertificate_cache = {
1273
+ tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1274
+ signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1275
+ signatureValue: readSignatureValue(certificate, blocks[2])
1276
+ };
1344
1277
  }
1345
- return modulus1.toString("hex") === modulus2.toString("hex");
1346
- }
1347
- function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1348
- const initialBuffer = Buffer.from("Lorem Ipsum");
1349
- const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1350
- const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1351
- const finalString = decryptedBuffer.toString("utf-8");
1352
- return initialBuffer.toString("utf-8") === finalString;
1278
+ return certificate_priv._exploreCertificate_cache;
1353
1279
  }
1354
- function certificateMatchesPrivateKey(certificate, privateKey) {
1355
- const e = explorePrivateKey(privateKey);
1356
- const blockSize = e.modulus.length;
1357
- const certificatePEM = toPem(certificate, "CERTIFICATE");
1358
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1280
+ function split_der(certificateChain) {
1281
+ const certificate_chain = [];
1282
+ do {
1283
+ const block_info = readTag(certificateChain, 0);
1284
+ const length = block_info.position + block_info.length;
1285
+ const der_certificate = certificateChain.subarray(0, length);
1286
+ certificate_chain.push(der_certificate);
1287
+ certificateChain = certificateChain.subarray(length);
1288
+ } while (certificateChain.length > 0);
1289
+ return certificate_chain;
1359
1290
  }
1360
-
1361
- // source/common.ts
1362
- var import_crypto2 = __toESM(require("crypto"));
1363
- var KeyObjectOrig = import_crypto2.default.KeyObject;
1364
- var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_crypto2.default;
1365
- function isKeyObject(mayBeKeyObject) {
1366
- if (KeyObjectOrig) {
1367
- return mayBeKeyObject instanceof KeyObjectOrig;
1291
+ function combine_der(certificates) {
1292
+ for (const cert of certificates) {
1293
+ const b = split_der(cert);
1294
+ let sum = 0;
1295
+ b.forEach((block) => {
1296
+ const block_info = readTag(block, 0);
1297
+ (0, import_node_assert4.default)(block_info.position + block_info.length === block.length);
1298
+ sum += block.length;
1299
+ });
1300
+ (0, import_node_assert4.default)(sum === cert.length);
1368
1301
  }
1369
- return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1302
+ return Buffer.concat(certificates);
1370
1303
  }
1371
- var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1372
- CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1373
- CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1374
- CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1375
- CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1376
- return CertificatePurpose2;
1377
- })(CertificatePurpose || {});
1378
1304
 
1379
1305
  // source/crypto_utils2.ts
1380
- var import_assert5 = __toESM(require("assert"));
1306
+ var import_node_assert5 = __toESM(require("assert"));
1381
1307
  var import_jsrsasign2 = __toESM(require("jsrsasign"));
1382
1308
  function rsaLengthPrivateKey(key) {
1383
1309
  const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
@@ -1388,8 +1314,8 @@ function toPem2(raw_key, pem) {
1388
1314
  if (raw_key.hidden) {
1389
1315
  return toPem2(raw_key.hidden, pem);
1390
1316
  }
1391
- (0, import_assert5.default)(raw_key, "expecting a key");
1392
- (0, import_assert5.default)(typeof pem === "string");
1317
+ (0, import_node_assert5.default)(raw_key, "expecting a key");
1318
+ (0, import_node_assert5.default)(typeof pem === "string");
1393
1319
  if (isKeyObject(raw_key)) {
1394
1320
  const _raw_key = raw_key;
1395
1321
  if (pem === "RSA PRIVATE KEY") {
@@ -1409,40 +1335,40 @@ function coercePublicKeyPem(publicKey) {
1409
1335
  if (isKeyObject(publicKey)) {
1410
1336
  return publicKey.export({ format: "pem", type: "spki" }).toString();
1411
1337
  }
1412
- (0, import_assert5.default)(typeof publicKey === "string");
1338
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1413
1339
  return publicKey;
1414
1340
  }
1415
1341
  function coerceRsaPublicKeyPem(publicKey) {
1416
1342
  if (isKeyObject(publicKey)) {
1417
1343
  return publicKey.export({ format: "pem", type: "spki" }).toString();
1418
1344
  }
1419
- (0, import_assert5.default)(typeof publicKey === "string");
1345
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1420
1346
  return publicKey;
1421
1347
  }
1422
1348
  function rsaLengthPublicKey(key) {
1423
1349
  key = coercePublicKeyPem(key);
1424
- (0, import_assert5.default)(typeof key === "string");
1350
+ (0, import_node_assert5.default)(typeof key === "string");
1425
1351
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1426
1352
  return a.n.toString(16).length / 2;
1427
1353
  }
1428
1354
  function rsaLengthRsaPublicKey(key) {
1429
1355
  key = coerceRsaPublicKeyPem(key);
1430
- (0, import_assert5.default)(typeof key === "string");
1356
+ (0, import_node_assert5.default)(typeof key === "string");
1431
1357
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1432
1358
  return a.n.toString(16).length / 2;
1433
1359
  }
1434
1360
 
1435
1361
  // source/derived_keys.ts
1436
- var import_assert7 = __toESM(require("assert"));
1437
- var import_crypto3 = require("crypto");
1362
+ var import_node_assert7 = __toESM(require("assert"));
1363
+ var import_node_crypto3 = require("crypto");
1438
1364
 
1439
1365
  // source/explore_certificate.ts
1440
- var import_assert6 = __toESM(require("assert"));
1366
+ var import_node_assert6 = __toESM(require("assert"));
1441
1367
  function coerceCertificate(certificate) {
1442
1368
  if (typeof certificate === "string") {
1443
1369
  certificate = convertPEMtoDER(certificate);
1444
1370
  }
1445
- (0, import_assert6.default)(Buffer.isBuffer(certificate));
1371
+ (0, import_node_assert6.default)(Buffer.isBuffer(certificate));
1446
1372
  return certificate;
1447
1373
  }
1448
1374
  function exploreCertificateInfo(certificate) {
@@ -1456,21 +1382,21 @@ function exploreCertificateInfo(certificate) {
1456
1382
  subject: certInfo.tbsCertificate.subject
1457
1383
  };
1458
1384
  if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1459
- throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1385
+ throw new Error(`Invalid public key length (expecting 128,256,384 or 512): ${data.publicKeyLength}`);
1460
1386
  }
1461
1387
  return data;
1462
1388
  }
1463
1389
 
1464
1390
  // source/derived_keys.ts
1465
1391
  function HMAC_HASH(sha1or256, secret, message) {
1466
- return (0, import_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1392
+ return (0, import_node_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1467
1393
  }
1468
1394
  function plus(buf1, buf2) {
1469
1395
  return Buffer.concat([buf1, buf2]);
1470
1396
  }
1471
1397
  function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1472
- (0, import_assert7.default)(Buffer.isBuffer(seed));
1473
- (0, import_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1398
+ (0, import_node_assert7.default)(Buffer.isBuffer(seed));
1399
+ (0, import_node_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1474
1400
  const a = [];
1475
1401
  a[0] = seed;
1476
1402
  let index = 1;
@@ -1483,12 +1409,12 @@ function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1483
1409
  return p_hash.subarray(0, minLength);
1484
1410
  }
1485
1411
  function computeDerivedKeys(secret, seed, options) {
1486
- (0, import_assert7.default)(Number.isFinite(options.signatureLength));
1487
- (0, import_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1488
- (0, import_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1489
- (0, import_assert7.default)(typeof options.algorithm === "string");
1412
+ (0, import_node_assert7.default)(Number.isFinite(options.signatureLength));
1413
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1414
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1415
+ (0, import_node_assert7.default)(typeof options.algorithm === "string");
1490
1416
  options.sha1or256 = options.sha1or256 || "SHA1";
1491
- (0, import_assert7.default)(typeof options.sha1or256 === "string");
1417
+ (0, import_node_assert7.default)(typeof options.sha1or256 === "string");
1492
1418
  const offset1 = options.signingKeyLength;
1493
1419
  const offset2 = offset1 + options.encryptingKeyLength;
1494
1420
  const minLength = offset2 + options.encryptingBlockSize;
@@ -1513,7 +1439,7 @@ function removePadding(buffer) {
1513
1439
  return reduceLength(buffer, nbPaddingBytes);
1514
1440
  }
1515
1441
  function verifyChunkSignature(chunk, options) {
1516
- (0, import_assert7.default)(Buffer.isBuffer(chunk));
1442
+ (0, import_node_assert7.default)(Buffer.isBuffer(chunk));
1517
1443
  let signatureLength = options.signatureLength || 0;
1518
1444
  if (signatureLength === 0) {
1519
1445
  const cert = exploreCertificateInfo(options.publicKey);
@@ -1524,23 +1450,23 @@ function verifyChunkSignature(chunk, options) {
1524
1450
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1525
1451
  }
1526
1452
  function computePaddingFooter(buffer, derivedKeys) {
1527
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1453
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "encryptingBlockSize"));
1528
1454
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1529
1455
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1530
1456
  padding.fill(paddingSize);
1531
1457
  return padding;
1532
1458
  }
1533
1459
  function derivedKeys_algorithm(derivedKeys) {
1534
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1460
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "algorithm"));
1535
1461
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1536
- (0, import_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1462
+ (0, import_node_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1537
1463
  return algorithm;
1538
1464
  }
1539
1465
  function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
1540
1466
  const algorithm = derivedKeys_algorithm(derivedKeys);
1541
1467
  const key = derivedKeys.encryptingKey;
1542
1468
  const initVector = derivedKeys.initializationVector;
1543
- const cipher = (0, import_crypto3.createCipheriv)(algorithm, key, initVector);
1469
+ const cipher = (0, import_node_crypto3.createCipheriv)(algorithm, key, initVector);
1544
1470
  cipher.setAutoPadding(false);
1545
1471
  const encrypted_chunks = [];
1546
1472
  encrypted_chunks.push(cipher.update(buffer));
@@ -1551,7 +1477,7 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1551
1477
  const algorithm = derivedKeys_algorithm(derivedKeys);
1552
1478
  const key = derivedKeys.encryptingKey;
1553
1479
  const initVector = derivedKeys.initializationVector;
1554
- const cipher = (0, import_crypto3.createDecipheriv)(algorithm, key, initVector);
1480
+ const cipher = (0, import_node_crypto3.createDecipheriv)(algorithm, key, initVector);
1555
1481
  cipher.setAutoPadding(false);
1556
1482
  const decrypted_chunks = [];
1557
1483
  decrypted_chunks.push(cipher.update(buffer));
@@ -1559,12 +1485,12 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1559
1485
  return Buffer.concat(decrypted_chunks);
1560
1486
  }
1561
1487
  function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1562
- (0, import_assert7.default)(Buffer.isBuffer(message));
1563
- (0, import_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1564
- (0, import_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1565
- (0, import_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1566
- const signature = (0, import_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1567
- (0, import_assert7.default)(signature.length === derivedKeys.signatureLength);
1488
+ (0, import_node_assert7.default)(Buffer.isBuffer(message));
1489
+ (0, import_node_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1490
+ (0, import_node_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1491
+ (0, import_node_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1492
+ const signature = (0, import_node_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1493
+ (0, import_node_assert7.default)(signature.length === derivedKeys.signatureLength);
1568
1494
  return signature;
1569
1495
  }
1570
1496
  function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
@@ -1609,7 +1535,7 @@ function _readTbsCertList(buffer, blockInfo) {
1609
1535
  const blocks = readStruct(buffer, blockInfo);
1610
1536
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1611
1537
  if (hasOptionalVersion) {
1612
- const version = readIntegerValue(buffer, blocks[0]);
1538
+ const _version = readIntegerValue(buffer, blocks[0]);
1613
1539
  const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1614
1540
  const issuer = readNameForCrl(buffer, blocks[2]);
1615
1541
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[2])));
@@ -1628,7 +1554,7 @@ function _readTbsCertList(buffer, blockInfo) {
1628
1554
  });
1629
1555
  }
1630
1556
  }
1631
- const ext0 = findBlockAtIndex(blocks, 0);
1557
+ const _ext0 = findBlockAtIndex(blocks, 0);
1632
1558
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1633
1559
  } else {
1634
1560
  const signature = readAlgorithmIdentifier(buffer, blocks[0]);
@@ -1668,10 +1594,21 @@ function _readExtensionRequest(buffer) {
1668
1594
  const extensions = inner_blocks.map((block1) => readExtension(buffer, block1));
1669
1595
  const result = {};
1670
1596
  for (const e of extensions) {
1671
- result[e.identifier.name] = e.value;
1597
+ switch (e.identifier.name) {
1598
+ case "basicConstraints":
1599
+ result.basicConstraints = e.value;
1600
+ break;
1601
+ case "keyUsage":
1602
+ result.keyUsage = e.value;
1603
+ break;
1604
+ case "subjectAltName":
1605
+ result.subjectAltName = e.value;
1606
+ break;
1607
+ default:
1608
+ break;
1609
+ }
1672
1610
  }
1673
- const { basicConstraints, keyUsage, subjectAltName } = result;
1674
- return { basicConstraints, keyUsage, subjectAltName };
1611
+ return result;
1675
1612
  }
1676
1613
  function readCertificationRequestInfo(buffer, block) {
1677
1614
  const blocks = readStruct(buffer, block);
@@ -1699,16 +1636,117 @@ function exploreCertificateSigningRequest(crl) {
1699
1636
  return csrInfo;
1700
1637
  }
1701
1638
 
1639
+ // source/explore_private_key.ts
1640
+ function f(buffer, b) {
1641
+ return buffer.subarray(b.position + 1, b.position + b.length);
1642
+ }
1643
+ var doDebug2 = !!process.env.DEBUG;
1644
+ function explorePrivateKey(privateKey2) {
1645
+ const privateKey1 = privateKey2.hidden;
1646
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1647
+ const block_info = readTag(privateKey, 0);
1648
+ const blocks = readStruct(privateKey, block_info);
1649
+ if (blocks.length === 9) {
1650
+ const version2 = f(privateKey, blocks[0]);
1651
+ const modulus2 = f(privateKey, blocks[1]);
1652
+ const publicExponent2 = f(privateKey, blocks[2]);
1653
+ const privateExponent2 = f(privateKey, blocks[3]);
1654
+ const prime12 = f(privateKey, blocks[4]);
1655
+ const prime22 = f(privateKey, blocks[5]);
1656
+ const exponent12 = f(privateKey, blocks[6]);
1657
+ const exponent22 = f(privateKey, blocks[7]);
1658
+ return {
1659
+ version: version2,
1660
+ modulus: modulus2,
1661
+ publicExponent: publicExponent2,
1662
+ privateExponent: privateExponent2,
1663
+ prime1: prime12,
1664
+ prime2: prime22,
1665
+ exponent1: exponent12,
1666
+ exponent2: exponent22
1667
+ };
1668
+ }
1669
+ if (doDebug2) {
1670
+ console.log("-------------------- private key:");
1671
+ console.log(block_info);
1672
+ console.log(
1673
+ blocks.map((b2) => ({
1674
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1675
+ l: b2.length,
1676
+ p: b2.position,
1677
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1678
+ }))
1679
+ );
1680
+ }
1681
+ const b = blocks[2];
1682
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1683
+ const block_info1 = readTag(bb, 0);
1684
+ const blocks1 = readStruct(bb, block_info1);
1685
+ if (doDebug2) {
1686
+ console.log(
1687
+ blocks1.map((b2) => ({
1688
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1689
+ l: b2.length,
1690
+ p: b2.position,
1691
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1692
+ }))
1693
+ );
1694
+ }
1695
+ const version = f(bb, blocks1[0]);
1696
+ const modulus = f(bb, blocks1[1]);
1697
+ const publicExponent = f(bb, blocks1[2]);
1698
+ const privateExponent = f(bb, blocks1[3]);
1699
+ const prime1 = f(bb, blocks1[4]);
1700
+ const prime2 = f(bb, blocks1[5]);
1701
+ const exponent1 = f(bb, blocks1[6]);
1702
+ const exponent2 = f(bb, blocks1[7]);
1703
+ return {
1704
+ version,
1705
+ modulus,
1706
+ publicExponent,
1707
+ privateExponent,
1708
+ prime1,
1709
+ prime2,
1710
+ exponent1,
1711
+ exponent2
1712
+ };
1713
+ }
1714
+
1702
1715
  // source/make_private_key_from_pem.ts
1703
1716
  function makePrivateKeyFromPem(privateKeyInPem) {
1704
1717
  return { hidden: privateKeyInPem };
1705
1718
  }
1706
1719
 
1707
1720
  // source/make_private_key_thumbprint.ts
1708
- function makePrivateKeyThumbPrint(privateKey) {
1721
+ function makePrivateKeyThumbPrint(_privateKey) {
1709
1722
  return Buffer.alloc(0);
1710
1723
  }
1711
1724
 
1725
+ // source/public_private_match.ts
1726
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1727
+ const i = exploreCertificate(certificate);
1728
+ const j = explorePrivateKey(privateKey);
1729
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1730
+ const modulus2 = j.modulus;
1731
+ if (modulus1.length !== modulus2.length) {
1732
+ return false;
1733
+ }
1734
+ return modulus1.toString("hex") === modulus2.toString("hex");
1735
+ }
1736
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1737
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1738
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1739
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1740
+ const finalString = decryptedBuffer.toString("utf-8");
1741
+ return initialBuffer.toString("utf-8") === finalString;
1742
+ }
1743
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1744
+ const e = explorePrivateKey(privateKey);
1745
+ const blockSize = e.modulus.length;
1746
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1747
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1748
+ }
1749
+
1712
1750
  // source/subject.ts
1713
1751
  var _keys = {
1714
1752
  C: "country",
@@ -1751,11 +1789,11 @@ var Subject = class _Subject {
1751
1789
  }
1752
1790
  const s = element.split("=");
1753
1791
  if (s.length !== 2) {
1754
- throw new Error("invalid format for " + element);
1792
+ throw new Error(`invalid format for ${element}`);
1755
1793
  }
1756
1794
  const longName = _keys[s[0]];
1757
1795
  if (!longName) {
1758
- throw new Error("Invalid field found in subject name " + s[0]);
1796
+ throw new Error(`Invalid field found in subject name ${s[0]}`);
1759
1797
  }
1760
1798
  const value = s[1];
1761
1799
  options[longName] = unquote(Buffer.from(value, "ascii").toString("utf8"));
@@ -1765,25 +1803,25 @@ var Subject = class _Subject {
1765
1803
  toStringInternal(sep) {
1766
1804
  const tmp = [];
1767
1805
  if (this.country) {
1768
- tmp.push("C=" + enquoteIfNecessary(this.country));
1806
+ tmp.push(`C=${enquoteIfNecessary(this.country)}`);
1769
1807
  }
1770
1808
  if (this.state) {
1771
- tmp.push("ST=" + enquoteIfNecessary(this.state));
1809
+ tmp.push(`ST=${enquoteIfNecessary(this.state)}`);
1772
1810
  }
1773
1811
  if (this.locality) {
1774
- tmp.push("L=" + enquoteIfNecessary(this.locality));
1812
+ tmp.push(`L=${enquoteIfNecessary(this.locality)}`);
1775
1813
  }
1776
1814
  if (this.organization) {
1777
- tmp.push("O=" + enquoteIfNecessary(this.organization));
1815
+ tmp.push(`O=${enquoteIfNecessary(this.organization)}`);
1778
1816
  }
1779
1817
  if (this.organizationalUnit) {
1780
- tmp.push("OU=" + enquoteIfNecessary(this.organizationalUnit));
1818
+ tmp.push(`OU=${enquoteIfNecessary(this.organizationalUnit)}`);
1781
1819
  }
1782
1820
  if (this.commonName) {
1783
- tmp.push("CN=" + enquoteIfNecessary(this.commonName));
1821
+ tmp.push(`CN=${enquoteIfNecessary(this.commonName)}`);
1784
1822
  }
1785
1823
  if (this.domainComponent) {
1786
- tmp.push("DC=" + enquoteIfNecessary(this.domainComponent));
1824
+ tmp.push(`DC=${enquoteIfNecessary(this.domainComponent)}`);
1787
1825
  }
1788
1826
  return tmp.join(sep);
1789
1827
  }
@@ -1792,12 +1830,12 @@ var Subject = class _Subject {
1792
1830
  }
1793
1831
  toString() {
1794
1832
  const t2 = this.toStringForOPCUA();
1795
- return t2 ? "/" + t2 : t2;
1833
+ return t2 ? `/${t2}` : t2;
1796
1834
  }
1797
1835
  };
1798
1836
 
1799
1837
  // source/verify_certificate_signature.ts
1800
- var import_crypto4 = require("crypto");
1838
+ var import_node_crypto4 = require("crypto");
1801
1839
  function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1802
1840
  const block_info = readTag(certificateOrCrl, 0);
1803
1841
  const blocks = readStruct(certificateOrCrl, block_info);
@@ -1806,7 +1844,7 @@ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1806
1844
  const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
1807
1845
  const p = split_der(parentCertificate)[0];
1808
1846
  const certPem = toPem(p, "CERTIFICATE");
1809
- const verify = (0, import_crypto4.createVerify)(signatureAlgorithm.identifier);
1847
+ const verify = (0, import_node_crypto4.createVerify)(signatureAlgorithm.identifier);
1810
1848
  verify.update(bufferToBeSigned);
1811
1849
  verify.end();
1812
1850
  return verify.verify(certPem, signatureValue);
@@ -1822,8 +1860,8 @@ async function verifyCertificateChain(certificateChain) {
1822
1860
  const cert = certificateChain[index - 1];
1823
1861
  const certParent = certificateChain[index];
1824
1862
  const certParentInfo = exploreCertificate(certParent);
1825
- const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1826
- if (!keyUsage.keyCertSign) {
1863
+ const keyUsage = certParentInfo.tbsCertificate.extensions?.keyUsage;
1864
+ if (!keyUsage || !keyUsage.keyCertSign) {
1827
1865
  return {
1828
1866
  status: "BadCertificateIssuerUseNotAllowed",
1829
1867
  reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
@@ -1863,15 +1901,15 @@ async function verifyCertificateChain(certificateChain) {
1863
1901
  }
1864
1902
 
1865
1903
  // source/x509/_crypto.ts
1866
- var x509 = __toESM(require("@peculiar/x509"));
1904
+ var import_node_crypto5 = __toESM(require("crypto"));
1867
1905
  var import_webcrypto = require("@peculiar/webcrypto");
1868
- var import_crypto5 = __toESM(require("crypto"));
1906
+ var x509 = __toESM(require("@peculiar/x509"));
1869
1907
  var x5092 = __toESM(require("@peculiar/x509"));
1870
1908
  var doDebug3 = false;
1871
1909
  var _crypto;
1872
1910
  var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1873
1911
  if (typeof window === "undefined") {
1874
- _crypto = import_crypto5.default;
1912
+ _crypto = import_node_crypto5.default;
1875
1913
  if (!_crypto?.subtle || ignoreCrypto) {
1876
1914
  _crypto = new import_webcrypto.Crypto();
1877
1915
  doDebug3 && console.warn("using @peculiar/webcrypto");
@@ -1885,7 +1923,7 @@ if (typeof window === "undefined") {
1885
1923
  x509.cryptoProvider.set(crypto);
1886
1924
  }
1887
1925
  function getCrypto() {
1888
- return _crypto || crypto || require("crypto");
1926
+ return _crypto || crypto || import_node_crypto5.default;
1889
1927
  }
1890
1928
 
1891
1929
  // source/x509/create_key_pair.ts
@@ -1911,7 +1949,7 @@ async function privateKeyToPEM(privateKey) {
1911
1949
  }
1912
1950
  async function derToPrivateKey(privDer) {
1913
1951
  const crypto3 = getCrypto();
1914
- return await crypto3.subtle.importKey(
1952
+ const importedKey = await crypto3.subtle.importKey(
1915
1953
  "pkcs8",
1916
1954
  privDer,
1917
1955
  {
@@ -1930,6 +1968,7 @@ async function derToPrivateKey(privDer) {
1930
1968
  // "deriveBits"
1931
1969
  ]
1932
1970
  );
1971
+ return importedKey;
1933
1972
  }
1934
1973
  async function pemToPrivateKey(pem) {
1935
1974
  const privDer = x5092.PemConverter.decode(pem);
@@ -1947,24 +1986,46 @@ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1947
1986
  throw new Error("not implemented");
1948
1987
  }
1949
1988
  async function _coercePrivateKey(privateKey) {
1950
- const KeyObject4 = crypto2.KeyObject;
1989
+ const KeyObject = crypto2.KeyObject;
1951
1990
  if (Buffer.isBuffer(privateKey)) {
1952
1991
  const privateKey1 = await derToPrivateKey(privateKey);
1953
- return KeyObject4.from(privateKey1);
1992
+ return KeyObject.from(privateKey1);
1954
1993
  } else if (typeof privateKey === "string") {
1955
1994
  try {
1956
1995
  const privateKey1 = await pemToPrivateKey(privateKey);
1957
- return KeyObject4.from(privateKey1);
1996
+ return KeyObject.from(privateKey1);
1958
1997
  } catch (err) {
1959
1998
  doDebug4 && console.log(privateKey);
1960
1999
  throw err;
1961
2000
  }
1962
- } else if (privateKey instanceof KeyObject4) {
2001
+ } else if (isKeyObject(privateKey)) {
1963
2002
  return privateKey;
1964
2003
  }
1965
2004
  throw new Error("Invalid privateKey");
1966
2005
  }
1967
2006
 
2007
+ // source/x509/_build_public_key.ts
2008
+ async function buildPublicKey(privateKey) {
2009
+ const crypto3 = getCrypto();
2010
+ const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
2011
+ delete jwk.d;
2012
+ delete jwk.dp;
2013
+ delete jwk.dq;
2014
+ delete jwk.q;
2015
+ delete jwk.qi;
2016
+ jwk.key_ops = [
2017
+ "encrypt",
2018
+ "sign"
2019
+ // "wrapKey"
2020
+ ];
2021
+ const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
2022
+ // "encrypt",
2023
+ // "sign",
2024
+ // "wrapKey",
2025
+ ]);
2026
+ return publicKey;
2027
+ }
2028
+
1968
2029
  // source/x509/_get_attributes.ts
1969
2030
  var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1970
2031
  var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
@@ -1973,19 +2034,19 @@ function getAttributes(purpose) {
1973
2034
  let keyUsageExtension = [];
1974
2035
  let usages;
1975
2036
  let nsComment;
1976
- let extension;
2037
+ let _extension;
1977
2038
  switch (purpose) {
1978
2039
  case 1 /* ForCertificateAuthority */:
1979
- extension = "v3_ca";
2040
+ _extension = "v3_ca";
1980
2041
  basicConstraints = new x5092.BasicConstraintsExtension(true, void 0, false);
1981
2042
  usages = keyUsageCA;
1982
2043
  keyUsageExtension = [];
1983
2044
  nsComment = "Self-signed certificate for CA generated by Node-OPCUA Certificate utility V2";
1984
2045
  break;
1985
- case 2 /* ForApplication */:
1986
- case 3 /* ForUserAuthentication */:
2046
+ // case CertificatePurpose.ForApplication:
2047
+ // case CertificatePurpose.ForUserAuthentication:
1987
2048
  default:
1988
- extension = "v3_selfsigned";
2049
+ _extension = "v3_selfsigned";
1989
2050
  basicConstraints = new x5092.BasicConstraintsExtension(false, void 0, true);
1990
2051
  usages = keyUsageApplication;
1991
2052
  keyUsageExtension = [x5092.ExtendedKeyUsage.serverAuth, x5092.ExtendedKeyUsage.clientAuth];
@@ -1995,28 +2056,6 @@ function getAttributes(purpose) {
1995
2056
  return { nsComment, basicConstraints, keyUsageExtension, usages };
1996
2057
  }
1997
2058
 
1998
- // source/x509/_build_public_key.ts
1999
- async function buildPublicKey(privateKey) {
2000
- const crypto3 = getCrypto();
2001
- const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
2002
- delete jwk.d;
2003
- delete jwk.dp;
2004
- delete jwk.dq;
2005
- delete jwk.q;
2006
- delete jwk.qi;
2007
- jwk.key_ops = [
2008
- "encrypt",
2009
- "sign"
2010
- // "wrapKey"
2011
- ];
2012
- const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
2013
- // "encrypt",
2014
- // "sign",
2015
- // "wrapKey",
2016
- ]);
2017
- return publicKey;
2018
- }
2019
-
2020
2059
  // source/x509/create_certificate_signing_request.ts
2021
2060
  async function createCertificateSigningRequest({
2022
2061
  privateKey,
@@ -2040,9 +2079,15 @@ async function createCertificateSigningRequest({
2040
2079
  publicKey
2041
2080
  };
2042
2081
  const alternativeNameExtensions = [];
2043
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
2044
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
2045
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
2082
+ for (const d of dns ?? []) {
2083
+ alternativeNameExtensions.push({ type: "dns", value: d });
2084
+ }
2085
+ for (const d of ip ?? []) {
2086
+ alternativeNameExtensions.push({ type: "ip", value: d });
2087
+ }
2088
+ if (applicationUri) {
2089
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
2090
+ }
2046
2091
  const { basicConstraints, usages } = getAttributes(purpose);
2047
2092
  const s = new Subject(subject || "");
2048
2093
  const s1 = s.toStringInternal(", ");
@@ -6336,9 +6381,19 @@ async function createSelfSignedCertificate({
6336
6381
  }
6337
6382
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6338
6383
  const alternativeNameExtensions = [];
6339
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6340
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6341
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
6384
+ if (dns) {
6385
+ for (const d of dns) {
6386
+ alternativeNameExtensions.push({ type: "dns", value: d });
6387
+ }
6388
+ }
6389
+ if (ip) {
6390
+ for (const d of ip) {
6391
+ alternativeNameExtensions.push({ type: "ip", value: d });
6392
+ }
6393
+ }
6394
+ if (applicationUri) {
6395
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
6396
+ }
6342
6397
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6343
6398
  const s = new Subject(subject || "");
6344
6399
  const s1 = s.toStringInternal(", ");