node-opcua-crypto 4.16.1 → 5.0.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.
package/dist/index.js CHANGED
@@ -119,8 +119,29 @@ __export(index_exports, {
119
119
  });
120
120
  module.exports = __toCommonJS(index_exports);
121
121
 
122
+ // source/common.ts
123
+ var import_node_crypto = __toESM(require("crypto"));
124
+ var KeyObjectOrig = import_node_crypto.default.KeyObject;
125
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_node_crypto.default;
126
+ function isKeyObject(mayBeKeyObject) {
127
+ if (KeyObjectOrig) {
128
+ return mayBeKeyObject instanceof KeyObjectOrig;
129
+ }
130
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
131
+ }
132
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
133
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
134
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
135
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
136
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
137
+ return CertificatePurpose2;
138
+ })(CertificatePurpose || {});
139
+
140
+ // source/crypto_explore_certificate.ts
141
+ var import_node_assert4 = __toESM(require("assert"));
142
+
122
143
  // source/asn1.ts
123
- var import_assert = __toESM(require("assert"));
144
+ var import_node_assert = __toESM(require("assert"));
124
145
 
125
146
  // source/oid_map.ts
126
147
  var oid_map = {
@@ -456,7 +477,7 @@ var TagType = /* @__PURE__ */ ((TagType2) => {
456
477
  function readTag(buf, pos) {
457
478
  const start = pos;
458
479
  if (buf.length <= pos) {
459
- throw new Error("Invalid position : buf.length=" + buf.length + " pos =" + pos);
480
+ throw new Error(`Invalid position : buf.length=${buf.length} pos=${pos}`);
460
481
  }
461
482
  const tag = buf.readUInt8(pos);
462
483
  pos += 1;
@@ -485,7 +506,8 @@ function readStruct(buf, blockInfo) {
485
506
  return blocks;
486
507
  }
487
508
  function parseBitString(buffer, start, end, maxLength) {
488
- const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = "(" + lenBit + " bit)\n";
509
+ const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = `(${lenBit} bit)
510
+ `;
489
511
  let s = "", skip = unusedBit;
490
512
  for (let i = end - 1; i > start; --i) {
491
513
  const b = buffer.readUInt8(i);
@@ -493,12 +515,12 @@ function parseBitString(buffer, start, end, maxLength) {
493
515
  s += b >> j & 1 ? "1" : "0";
494
516
  }
495
517
  skip = 0;
496
- (0, import_assert.default)(s.length <= maxLength);
518
+ (0, import_node_assert.default)(s.length <= maxLength);
497
519
  }
498
520
  return intro + s;
499
521
  }
500
522
  function readBitString(buffer, block) {
501
- (0, import_assert.default)(block.tag === 3 /* BIT_STRING */);
523
+ (0, import_node_assert.default)(block.tag === 3 /* BIT_STRING */);
502
524
  const data = getBlock(buffer, block);
503
525
  const ignore_bits = data.readUInt8(0);
504
526
  return {
@@ -511,14 +533,14 @@ function readBitString(buffer, block) {
511
533
  function formatBuffer2DigitHexWithColum(buffer) {
512
534
  const value = [];
513
535
  for (let i = 0; i < buffer.length; i++) {
514
- value.push(("00" + buffer.readUInt8(i).toString(16)).substr(-2, 2));
536
+ value.push(`00${buffer.readUInt8(i).toString(16)}`.substr(-2, 2));
515
537
  }
516
538
  return value.join(":").toUpperCase().replace(/^(00:)*/, "");
517
539
  }
518
540
  function readOctetString(buffer, block) {
519
- (0, import_assert.default)(block.tag === 4 /* OCTET_STRING */);
541
+ (0, import_node_assert.default)(block.tag === 4 /* OCTET_STRING */);
520
542
  const tag = readTag(buffer, block.position);
521
- (0, import_assert.default)(tag.tag === 4 /* OCTET_STRING */);
543
+ (0, import_node_assert.default)(tag.tag === 4 /* OCTET_STRING */);
522
544
  const nbBytes = tag.length;
523
545
  const pos = tag.position;
524
546
  const b = buffer.subarray(pos, pos + nbBytes);
@@ -548,19 +570,19 @@ function parseOID(buffer, start, end) {
548
570
  if (!(v & 128)) {
549
571
  if (s === "") {
550
572
  const m = n < 80 ? n < 40 ? 0 : 1 : 2;
551
- s = m + "." + (n - m * 40);
573
+ s = `${m}.${n - m * 40}`;
552
574
  } else {
553
- s += "." + n.toString();
575
+ s += `.${n.toString()}`;
554
576
  }
555
577
  n = 0;
556
578
  bits = 0;
557
579
  }
558
580
  }
559
- (0, import_assert.default)(bits === 0);
581
+ (0, import_node_assert.default)(bits === 0);
560
582
  return s;
561
583
  }
562
584
  function readObjectIdentifier(buffer, block) {
563
- (0, import_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
585
+ (0, import_node_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
564
586
  const b = buffer.subarray(block.position, block.position + block.length);
565
587
  const oid = parseOID(b, 0, block.length);
566
588
  return {
@@ -588,17 +610,17 @@ function readSignatureValue(buffer, block) {
588
610
  return readSignatureValueBin(buffer, block).toString("hex");
589
611
  }
590
612
  function readLongIntegerValue(buffer, block) {
591
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
613
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
592
614
  const pos = block.position;
593
615
  const nbBytes = block.length;
594
616
  const buf = buffer.subarray(pos, pos + nbBytes);
595
617
  return buf;
596
618
  }
597
619
  function readIntegerValue(buffer, block) {
598
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
620
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
599
621
  let pos = block.position;
600
622
  const nbBytes = block.length;
601
- (0, import_assert.default)(nbBytes < 4);
623
+ (0, import_node_assert.default)(nbBytes < 4);
602
624
  let value = 0;
603
625
  for (let i = 0; i < nbBytes; i++) {
604
626
  value = value * 256 + buffer.readUInt8(pos);
@@ -607,11 +629,11 @@ function readIntegerValue(buffer, block) {
607
629
  return value;
608
630
  }
609
631
  function readBooleanValue(buffer, block) {
610
- (0, import_assert.default)(block.tag === 1 /* BOOLEAN */, "expecting a BOOLEAN tag. got " + TagType[block.tag]);
632
+ (0, import_node_assert.default)(block.tag === 1 /* BOOLEAN */, `expecting a BOOLEAN tag. got ${TagType[block.tag]}`);
611
633
  const pos = block.position;
612
634
  const nbBytes = block.length;
613
- (0, import_assert.default)(nbBytes < 4);
614
- const value = buffer.readUInt8(pos) ? true : false;
635
+ (0, import_node_assert.default)(nbBytes < 4);
636
+ const value = !!buffer.readUInt8(pos);
615
637
  return value;
616
638
  }
617
639
  function readVersionValue(buffer, block) {
@@ -663,7 +685,7 @@ function readValue(buffer, block) {
663
685
  case 24 /* GeneralizedTime */:
664
686
  return convertGeneralizedTime(getBlock(buffer, block).toString("ascii"));
665
687
  default:
666
- throw new Error("Invalid tag 0x" + block.tag.toString(16));
688
+ throw new Error(`Invalid tag 0x${block.tag.toString(16)}`);
667
689
  }
668
690
  }
669
691
  function findBlockAtIndex(blocks, index) {
@@ -678,31 +700,229 @@ function readTime(buffer, block) {
678
700
  }
679
701
 
680
702
  // source/crypto_utils.ts
681
- var import_constants = __toESM(require("constants"));
682
- var import_assert4 = __toESM(require("assert"));
683
- var import_crypto = require("crypto");
684
- var import_hexy = __toESM(require("hexy"));
703
+ var import_node_assert2 = __toESM(require("assert"));
704
+ var import_node_constants = __toESM(require("constants"));
705
+ var import_node_crypto2 = require("crypto");
706
+ var import_jsrsasign = __toESM(require("jsrsasign"));
685
707
 
686
708
  // source/buffer_utils.ts
687
709
  var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (size) => {
688
710
  return new Buffer(size);
689
711
  };
690
712
 
691
- // source/crypto_explore_certificate.ts
692
- var import_assert3 = __toESM(require("assert"));
713
+ // source/hexy.ts
714
+ function hexy(buffer, { width, format } = {}) {
715
+ width = width || 80;
716
+ if (format === "twos") {
717
+ width = 26 * 3;
718
+ }
719
+ const regex = new RegExp(`.{1,${width}}`, "g");
720
+ const regexTwos = new RegExp(`.{1,${2}}`, "g");
721
+ let fullHex = buffer.toString("hex");
722
+ if (format === "twos") {
723
+ fullHex = fullHex.match(regexTwos)?.join(" ") || "";
724
+ }
725
+ return fullHex.match(regex)?.join("\n") || "";
726
+ }
727
+
728
+ // source/crypto_utils.ts
729
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
730
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
731
+ function identifyPemType(rawKey) {
732
+ if (Buffer.isBuffer(rawKey)) {
733
+ rawKey = rawKey.toString("utf8");
734
+ }
735
+ const match = PEM_TYPE_REGEX.exec(rawKey);
736
+ return !match ? void 0 : match[2];
737
+ }
738
+ function removeTrailingLF(str) {
739
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
740
+ return tmp;
741
+ }
742
+ function toPem(raw_key, pem) {
743
+ (0, import_node_assert2.default)(raw_key, "expecting a key");
744
+ (0, import_node_assert2.default)(typeof pem === "string");
745
+ let pemType = identifyPemType(raw_key);
746
+ if (pemType) {
747
+ return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
748
+ } else {
749
+ pemType = pem;
750
+ (0, import_node_assert2.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
751
+ let b = raw_key.toString("base64");
752
+ let str = `-----BEGIN ${pemType}-----
753
+ `;
754
+ while (b.length) {
755
+ str += `${b.substring(0, 64)}
756
+ `;
757
+ b = b.substring(64);
758
+ }
759
+ str += `-----END ${pemType}-----`;
760
+ return str;
761
+ }
762
+ }
763
+ function convertPEMtoDER(raw_key) {
764
+ let match;
765
+ let _pemType;
766
+ let base64str;
767
+ const parts = [];
768
+ PEM_REGEX.lastIndex = 0;
769
+ match = PEM_REGEX.exec(raw_key);
770
+ while (match !== null) {
771
+ _pemType = match[2];
772
+ base64str = match[3];
773
+ base64str = base64str.replace(/\r?\n/g, "");
774
+ parts.push(Buffer.from(base64str, "base64"));
775
+ match = PEM_REGEX.exec(raw_key);
776
+ }
777
+ return combine_der(parts);
778
+ }
779
+ function hexDump(buffer, width) {
780
+ if (!buffer) {
781
+ return "<>";
782
+ }
783
+ width = width || 32;
784
+ if (buffer.length > 1024) {
785
+ return `${hexy(buffer.subarray(0, 1024), { width, format: "twos" })}
786
+ .... ( ${buffer.length})`;
787
+ } else {
788
+ return hexy(buffer, { width, format: "twos" });
789
+ }
790
+ }
791
+ function makeMessageChunkSignature(chunk, options) {
792
+ const signer = (0, import_node_crypto2.createSign)(options.algorithm);
793
+ signer.update(chunk);
794
+ const signature = signer.sign(options.privateKey.hidden);
795
+ (0, import_node_assert2.default)(!options.signatureLength || signature.length === options.signatureLength);
796
+ return signature;
797
+ }
798
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
799
+ const verify = (0, import_node_crypto2.createVerify)(options.algorithm);
800
+ verify.update(blockToVerify);
801
+ return verify.verify(options.publicKey, signature);
802
+ }
803
+ function makeSHA1Thumbprint(buffer) {
804
+ return (0, import_node_crypto2.createHash)("sha1").update(buffer).digest();
805
+ }
806
+ var RSA_PKCS1_OAEP_PADDING = import_node_constants.default.RSA_PKCS1_OAEP_PADDING;
807
+ var RSA_PKCS1_PADDING = import_node_constants.default.RSA_PKCS1_PADDING;
808
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
809
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
810
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
811
+ return PaddingAlgorithm2;
812
+ })(PaddingAlgorithm || {});
813
+ (0, import_node_assert2.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_node_constants.default.RSA_PKCS1_OAEP_PADDING);
814
+ (0, import_node_assert2.default)(1 /* RSA_PKCS1_PADDING */ === import_node_constants.default.RSA_PKCS1_PADDING);
815
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
816
+ if (algorithm === void 0) {
817
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
818
+ }
819
+ return (0, import_node_crypto2.publicEncrypt)(
820
+ {
821
+ key: publicKey,
822
+ padding: algorithm
823
+ },
824
+ buffer
825
+ );
826
+ }
827
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
828
+ if (algorithm === void 0) {
829
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
830
+ }
831
+ try {
832
+ return (0, import_node_crypto2.privateDecrypt)(
833
+ {
834
+ key: privateKey.hidden,
835
+ padding: algorithm
836
+ },
837
+ buffer
838
+ );
839
+ } catch (_err) {
840
+ return Buffer.alloc(1);
841
+ }
842
+ }
843
+ var publicEncrypt = publicEncrypt_native;
844
+ var privateDecrypt = privateDecrypt_native;
845
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
846
+ if (paddingAlgorithm === void 0) {
847
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
848
+ }
849
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
850
+ padding = padding || 11;
851
+ if (padding !== 11) throw new Error("padding should be 11");
852
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
853
+ padding = padding || 42;
854
+ if (padding !== 42) throw new Error("padding should be 42");
855
+ } else {
856
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
857
+ }
858
+ const chunk_size = blockSize - padding;
859
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
860
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
861
+ for (let i = 0; i < nbBlocks; i++) {
862
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
863
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
864
+ if (encrypted_chunk.length !== blockSize) {
865
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
866
+ }
867
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
868
+ }
869
+ return outputBuffer;
870
+ }
871
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
872
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
873
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
874
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
875
+ }
876
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
877
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
878
+ let total_length = 0;
879
+ for (let i = 0; i < nbBlocks; i++) {
880
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
881
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
882
+ decrypted_buf.copy(outputBuffer, total_length);
883
+ total_length += decrypted_buf.length;
884
+ }
885
+ return outputBuffer.subarray(0, total_length);
886
+ }
887
+ function coerceCertificatePem(certificate) {
888
+ if (Buffer.isBuffer(certificate)) {
889
+ certificate = toPem(certificate, "CERTIFICATE");
890
+ }
891
+ (0, import_node_assert2.default)(typeof certificate === "string");
892
+ return certificate;
893
+ }
894
+ function extractPublicKeyFromCertificateSync(certificate) {
895
+ certificate = coerceCertificatePem(certificate);
896
+ const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
897
+ const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
898
+ (0, import_node_assert2.default)(typeof publicKeyAsPem === "string");
899
+ return publicKeyAsPem;
900
+ }
901
+ function extractPublicKeyFromCertificate(certificate, callback) {
902
+ let err1 = null;
903
+ let keyPem;
904
+ try {
905
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
906
+ } catch (err) {
907
+ err1 = err;
908
+ }
909
+ setImmediate(() => {
910
+ callback(err1, keyPem);
911
+ });
912
+ }
693
913
 
694
914
  // source/directory_name.ts
695
- var import_assert2 = __toESM(require("assert"));
915
+ var import_node_assert3 = __toESM(require("assert"));
696
916
  function readDirectoryName(buffer, block) {
697
917
  const set_blocks = readStruct(buffer, block);
698
918
  const names = {};
699
919
  for (const set_block of set_blocks) {
700
- (0, import_assert2.default)(set_block.tag === 49);
920
+ (0, import_node_assert3.default)(set_block.tag === 49);
701
921
  const blocks = readStruct(buffer, set_block);
702
- (0, import_assert2.default)(blocks.length === 1);
703
- (0, import_assert2.default)(blocks[0].tag === 48);
922
+ (0, import_node_assert3.default)(blocks.length === 1);
923
+ (0, import_node_assert3.default)(blocks[0].tag === 48);
704
924
  const sequenceBlock = readStruct(buffer, blocks[0]);
705
- (0, import_assert2.default)(sequenceBlock.length === 2);
925
+ (0, import_node_assert3.default)(sequenceBlock.length === 2);
706
926
  const type = readObjectIdentifier(buffer, sequenceBlock[0]);
707
927
  names[type.name] = readValue(buffer, sequenceBlock[1]);
708
928
  }
@@ -782,7 +1002,7 @@ function _readAuthorityKeyIdentifier(buffer) {
782
1002
  // can be null for self-signed certf
783
1003
  };
784
1004
  }
785
- function readBasicConstraint2_5_29_19(buffer, block) {
1005
+ function readBasicConstraint2_5_29_19(buffer, _block) {
786
1006
  const block_info = readTag(buffer, 0);
787
1007
  const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
788
1008
  let cA = false;
@@ -827,14 +1047,14 @@ function _readGeneralNames(buffer, block) {
827
1047
  }
828
1048
  const n = {};
829
1049
  for (const block2 of blocks) {
830
- (0, import_assert3.default)((block2.tag & 128) === 128);
1050
+ (0, import_node_assert4.default)((block2.tag & 128) === 128);
831
1051
  const t2 = block2.tag & 127;
832
1052
  const type = _data[t2];
833
1053
  if (!type) {
834
- console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
1054
+ console.log(`_readGeneralNames: INVALID TYPE => ${t2} 0x${t2.toString(16)}`);
835
1055
  continue;
836
1056
  }
837
- if (t2 == 32) {
1057
+ if (t2 === 32) {
838
1058
  n[type.name] = n[type.name] || [];
839
1059
  const blocks2 = readStruct(buffer, block2);
840
1060
  const name = readObjectIdentifier(buffer, blocks2[0]).name;
@@ -857,7 +1077,7 @@ function _readSubjectAltNames(buffer) {
857
1077
  const block_info = readTag(buffer, 0);
858
1078
  return _readGeneralNames(buffer, block_info);
859
1079
  }
860
- function readKeyUsage(oid, buffer) {
1080
+ function readKeyUsage(_oid, buffer) {
861
1081
  const block_info = readTag(buffer, 0);
862
1082
  let b2 = 0;
863
1083
  let b3 = 0;
@@ -887,7 +1107,7 @@ function readKeyUsage(oid, buffer) {
887
1107
  };
888
1108
  }
889
1109
  function readExtKeyUsage(oid, buffer) {
890
- (0, import_assert3.default)(oid === "2.5.29.37");
1110
+ (0, import_node_assert4.default)(oid === "2.5.29.37");
891
1111
  const block_info = readTag(buffer, 0);
892
1112
  const inner_blocks = readStruct(buffer, block_info);
893
1113
  const extKeyUsage = {
@@ -917,7 +1137,7 @@ function _readSubjectPublicKey(buffer) {
917
1137
  function readExtension(buffer, block) {
918
1138
  const inner_blocks = readStruct(buffer, block);
919
1139
  if (inner_blocks.length === 3) {
920
- (0, import_assert3.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
1140
+ (0, import_node_assert4.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
921
1141
  inner_blocks[1] = inner_blocks[2];
922
1142
  }
923
1143
  const identifier = readObjectIdentifier(buffer, inner_blocks[0]);
@@ -937,7 +1157,7 @@ function readExtension(buffer, block) {
937
1157
  value = readBasicConstraint2_5_29_19(buf, inner_blocks[1]);
938
1158
  break;
939
1159
  case "certExtension":
940
- value = "basicConstraints ( not implemented yet) " + buf.toString("hex");
1160
+ value = `basicConstraints ( not implemented yet) ${buf.toString("hex")}`;
941
1161
  break;
942
1162
  case "extKeyUsage":
943
1163
  value = readExtKeyUsage(identifier.oid, buf);
@@ -946,7 +1166,7 @@ function readExtension(buffer, block) {
946
1166
  value = readKeyUsage(identifier.oid, buf);
947
1167
  break;
948
1168
  default:
949
- value = "Unknown " + identifier.name + buf.toString("hex");
1169
+ value = `Unknown ${identifier.name}${buf.toString("hex")}`;
950
1170
  }
951
1171
  return {
952
1172
  identifier,
@@ -954,7 +1174,7 @@ function readExtension(buffer, block) {
954
1174
  };
955
1175
  }
956
1176
  function _readExtensions(buffer, block) {
957
- (0, import_assert3.default)(block.tag === 163);
1177
+ (0, import_node_assert4.default)(block.tag === 163);
958
1178
  let inner_blocks = readStruct(buffer, block);
959
1179
  inner_blocks = readStruct(buffer, inner_blocks[0]);
960
1180
  const extensions = inner_blocks.map((block2) => readExtension(buffer, block2));
@@ -993,10 +1213,17 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
993
1213
  }
994
1214
  function readTbsCertificate(buffer, block) {
995
1215
  const blocks = readStruct(buffer, block);
996
- let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1216
+ let _version;
1217
+ let serialNumber;
1218
+ let signature;
1219
+ let issuer;
1220
+ let validity;
1221
+ let subject;
1222
+ let subjectFingerPrint;
1223
+ let extensions;
997
1224
  let subjectPublicKeyInfo;
998
1225
  if (blocks.length === 6) {
999
- version = 1;
1226
+ _version = 1;
1000
1227
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[0]));
1001
1228
  signature = readAlgorithmIdentifier(buffer, blocks[1]);
1002
1229
  issuer = _readName(buffer, blocks[2]);
@@ -1010,7 +1237,7 @@ function readTbsCertificate(buffer, block) {
1010
1237
  if (!version_block) {
1011
1238
  throw new Error("cannot find version block");
1012
1239
  }
1013
- version = readVersionValue(buffer, version_block) + 1;
1240
+ _version = readVersionValue(buffer, version_block) + 1;
1014
1241
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[1]));
1015
1242
  signature = readAlgorithmIdentifier(buffer, blocks[2]);
1016
1243
  issuer = _readName(buffer, blocks[3]);
@@ -1024,22 +1251,22 @@ function readTbsCertificate(buffer, block) {
1024
1251
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
1025
1252
  break;
1026
1253
  }
1027
- case "ecPublicKey":
1028
1254
  default: {
1255
+ (0, import_node_assert4.default)(what_type === "ecPublicKey");
1029
1256
  subjectPublicKeyInfo = _readSubjectECCPublicKeyInfo(buffer, blocks[6]);
1030
1257
  break;
1031
1258
  }
1032
1259
  }
1033
1260
  const extensionBlock = findBlockAtIndex(blocks, 3);
1034
1261
  if (!extensionBlock) {
1035
- doDebug && console.log("X509 certificate is invalid : cannot find extension block version =" + version_block);
1262
+ doDebug && console.log(`X509 certificate is invalid : cannot find extension block version = ${version_block}`);
1036
1263
  extensions = null;
1037
1264
  } else {
1038
1265
  extensions = _readExtensions(buffer, extensionBlock);
1039
1266
  }
1040
1267
  }
1041
1268
  return {
1042
- version,
1269
+ version: _version,
1043
1270
  serialNumber,
1044
1271
  signature,
1045
1272
  issuer,
@@ -1050,348 +1277,47 @@ function readTbsCertificate(buffer, block) {
1050
1277
  extensions
1051
1278
  };
1052
1279
  }
1053
- function exploreCertificate(certificate) {
1054
- (0, import_assert3.default)(Buffer.isBuffer(certificate));
1055
- if (!certificate._exploreCertificate_cache) {
1056
- const block_info = readTag(certificate, 0);
1057
- const blocks = readStruct(certificate, block_info);
1058
- certificate._exploreCertificate_cache = {
1059
- tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1060
- signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1061
- signatureValue: readSignatureValue(certificate, blocks[2])
1062
- };
1063
- }
1064
- return certificate._exploreCertificate_cache;
1065
- }
1066
- function split_der(certificateChain) {
1067
- const certificate_chain = [];
1068
- do {
1069
- const block_info = readTag(certificateChain, 0);
1070
- const length = block_info.position + block_info.length;
1071
- const der_certificate = certificateChain.subarray(0, length);
1072
- certificate_chain.push(der_certificate);
1073
- certificateChain = certificateChain.subarray(length);
1074
- } while (certificateChain.length > 0);
1075
- return certificate_chain;
1076
- }
1077
- function combine_der(certificates) {
1078
- for (const cert of certificates) {
1079
- const b = split_der(cert);
1080
- let sum = 0;
1081
- b.forEach((block) => {
1082
- const block_info = readTag(block, 0);
1083
- (0, import_assert3.default)(block_info.position + block_info.length === block.length);
1084
- sum += block.length;
1085
- });
1086
- (0, import_assert3.default)(sum === cert.length);
1087
- }
1088
- return Buffer.concat(certificates);
1089
- }
1090
-
1091
- // source/crypto_utils.ts
1092
- var import_jsrsasign = __toESM(require("jsrsasign"));
1093
- var { hexy } = import_hexy.default;
1094
- var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
1095
- var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
1096
- function identifyPemType(rawKey) {
1097
- if (Buffer.isBuffer(rawKey)) {
1098
- rawKey = rawKey.toString("utf8");
1099
- }
1100
- const match = PEM_TYPE_REGEX.exec(rawKey);
1101
- return !match ? void 0 : match[2];
1102
- }
1103
- function removeTrailingLF(str) {
1104
- const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1105
- return tmp;
1106
- }
1107
- function toPem(raw_key, pem) {
1108
- (0, import_assert4.default)(raw_key, "expecting a key");
1109
- (0, import_assert4.default)(typeof pem === "string");
1110
- let pemType = identifyPemType(raw_key);
1111
- if (pemType) {
1112
- return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1113
- } else {
1114
- pemType = pem;
1115
- (0, import_assert4.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1116
- let b = raw_key.toString("base64");
1117
- let str = "-----BEGIN " + pemType + "-----\n";
1118
- while (b.length) {
1119
- str += b.substring(0, 64) + "\n";
1120
- b = b.substring(64);
1121
- }
1122
- str += "-----END " + pemType + "-----";
1123
- return str;
1124
- }
1125
- }
1126
- function convertPEMtoDER(raw_key) {
1127
- let match;
1128
- let pemType;
1129
- let base64str;
1130
- const parts = [];
1131
- PEM_REGEX.lastIndex = 0;
1132
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1133
- pemType = match[2];
1134
- base64str = match[3];
1135
- base64str = base64str.replace(/\r?\n/g, "");
1136
- parts.push(Buffer.from(base64str, "base64"));
1137
- }
1138
- return combine_der(parts);
1139
- }
1140
- function hexDump(buffer, width) {
1141
- if (!buffer) {
1142
- return "<>";
1143
- }
1144
- width = width || 32;
1145
- if (buffer.length > 1024) {
1146
- return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1147
- } else {
1148
- return hexy(buffer, { width, format: "twos" });
1149
- }
1150
- }
1151
- function makeMessageChunkSignature(chunk, options) {
1152
- const signer = (0, import_crypto.createSign)(options.algorithm);
1153
- signer.update(chunk);
1154
- const signature = signer.sign(options.privateKey.hidden);
1155
- (0, import_assert4.default)(!options.signatureLength || signature.length === options.signatureLength);
1156
- return signature;
1157
- }
1158
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
1159
- const verify = (0, import_crypto.createVerify)(options.algorithm);
1160
- verify.update(blockToVerify);
1161
- return verify.verify(options.publicKey, signature);
1162
- }
1163
- function makeSHA1Thumbprint(buffer) {
1164
- return (0, import_crypto.createHash)("sha1").update(buffer).digest();
1165
- }
1166
- var RSA_PKCS1_OAEP_PADDING = import_constants.default.RSA_PKCS1_OAEP_PADDING;
1167
- var RSA_PKCS1_PADDING = import_constants.default.RSA_PKCS1_PADDING;
1168
- var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1169
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1170
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1171
- return PaddingAlgorithm2;
1172
- })(PaddingAlgorithm || {});
1173
- (0, import_assert4.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_constants.default.RSA_PKCS1_OAEP_PADDING);
1174
- (0, import_assert4.default)(1 /* RSA_PKCS1_PADDING */ === import_constants.default.RSA_PKCS1_PADDING);
1175
- function publicEncrypt_native(buffer, publicKey, algorithm) {
1176
- if (algorithm === void 0) {
1177
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1178
- }
1179
- return (0, import_crypto.publicEncrypt)(
1180
- {
1181
- key: publicKey,
1182
- padding: algorithm
1183
- },
1184
- buffer
1185
- );
1186
- }
1187
- function privateDecrypt_native(buffer, privateKey, algorithm) {
1188
- if (algorithm === void 0) {
1189
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1190
- }
1191
- try {
1192
- return (0, import_crypto.privateDecrypt)(
1193
- {
1194
- key: privateKey.hidden,
1195
- padding: algorithm
1196
- },
1197
- buffer
1198
- );
1199
- } catch (err) {
1200
- return Buffer.alloc(1);
1201
- }
1202
- }
1203
- var publicEncrypt = publicEncrypt_native;
1204
- var privateDecrypt = privateDecrypt_native;
1205
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1206
- if (paddingAlgorithm === void 0) {
1207
- paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1208
- }
1209
- if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1210
- padding = padding || 11;
1211
- if (padding !== 11) throw new Error("padding should be 11");
1212
- } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1213
- padding = padding || 42;
1214
- if (padding !== 42) throw new Error("padding should be 42");
1215
- } else {
1216
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1217
- }
1218
- const chunk_size = blockSize - padding;
1219
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
1220
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1221
- for (let i = 0; i < nbBlocks; i++) {
1222
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1223
- const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1224
- if (encrypted_chunk.length !== blockSize) {
1225
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1226
- }
1227
- encrypted_chunk.copy(outputBuffer, i * blockSize);
1228
- }
1229
- return outputBuffer;
1230
- }
1231
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1232
- paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1233
- if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1234
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1235
- }
1236
- const nbBlocks = Math.ceil(buffer.length / blockSize);
1237
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1238
- let total_length = 0;
1239
- for (let i = 0; i < nbBlocks; i++) {
1240
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1241
- const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1242
- decrypted_buf.copy(outputBuffer, total_length);
1243
- total_length += decrypted_buf.length;
1244
- }
1245
- return outputBuffer.subarray(0, total_length);
1246
- }
1247
- function coerceCertificatePem(certificate) {
1248
- if (Buffer.isBuffer(certificate)) {
1249
- certificate = toPem(certificate, "CERTIFICATE");
1250
- }
1251
- (0, import_assert4.default)(typeof certificate === "string");
1252
- return certificate;
1253
- }
1254
- function extractPublicKeyFromCertificateSync(certificate) {
1255
- certificate = coerceCertificatePem(certificate);
1256
- const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
1257
- const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
1258
- (0, import_assert4.default)(typeof publicKeyAsPem === "string");
1259
- return publicKeyAsPem;
1260
- }
1261
- function extractPublicKeyFromCertificate(certificate, callback) {
1262
- let err1 = null;
1263
- let keyPem;
1264
- try {
1265
- keyPem = extractPublicKeyFromCertificateSync(certificate);
1266
- } catch (err) {
1267
- err1 = err;
1268
- }
1269
- setImmediate(() => {
1270
- callback(err1, keyPem);
1271
- });
1272
- }
1273
-
1274
- // source/explore_private_key.ts
1275
- function f(buffer, b) {
1276
- return buffer.subarray(b.position + 1, b.position + b.length);
1277
- }
1278
- var doDebug2 = !!process.env.DEBUG;
1279
- function explorePrivateKey(privateKey2) {
1280
- const privateKey1 = privateKey2.hidden;
1281
- const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1282
- const block_info = readTag(privateKey, 0);
1283
- const blocks = readStruct(privateKey, block_info);
1284
- if (blocks.length === 9) {
1285
- const version2 = f(privateKey, blocks[0]);
1286
- const modulus2 = f(privateKey, blocks[1]);
1287
- const publicExponent2 = f(privateKey, blocks[2]);
1288
- const privateExponent2 = f(privateKey, blocks[3]);
1289
- const prime12 = f(privateKey, blocks[4]);
1290
- const prime22 = f(privateKey, blocks[5]);
1291
- const exponent12 = f(privateKey, blocks[6]);
1292
- const exponent22 = f(privateKey, blocks[7]);
1293
- return {
1294
- version: version2,
1295
- modulus: modulus2,
1296
- publicExponent: publicExponent2,
1297
- privateExponent: privateExponent2,
1298
- prime1: prime12,
1299
- prime2: prime22,
1300
- exponent1: exponent12,
1301
- exponent2: exponent22
1302
- };
1303
- }
1304
- if (doDebug2) {
1305
- console.log("-------------------- private key:");
1306
- console.log(block_info);
1307
- console.log(
1308
- blocks.map((b2) => ({
1309
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1310
- l: b2.length,
1311
- p: b2.position,
1312
- buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1313
- }))
1314
- );
1315
- }
1316
- const b = blocks[2];
1317
- const bb = privateKey.subarray(b.position, b.position + b.length);
1318
- const block_info1 = readTag(bb, 0);
1319
- const blocks1 = readStruct(bb, block_info1);
1320
- if (doDebug2) {
1321
- console.log(
1322
- blocks1.map((b2) => ({
1323
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1324
- l: b2.length,
1325
- p: b2.position,
1326
- buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1327
- }))
1328
- );
1329
- }
1330
- const version = f(bb, blocks1[0]);
1331
- const modulus = f(bb, blocks1[1]);
1332
- const publicExponent = f(bb, blocks1[2]);
1333
- const privateExponent = f(bb, blocks1[3]);
1334
- const prime1 = f(bb, blocks1[4]);
1335
- const prime2 = f(bb, blocks1[5]);
1336
- const exponent1 = f(bb, blocks1[6]);
1337
- const exponent2 = f(bb, blocks1[7]);
1338
- return {
1339
- version,
1340
- modulus,
1341
- publicExponent,
1342
- privateExponent,
1343
- prime1,
1344
- prime2,
1345
- exponent1,
1346
- exponent2
1347
- };
1348
- }
1349
-
1350
- // source/public_private_match.ts
1351
- function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1352
- const i = exploreCertificate(certificate);
1353
- const j = explorePrivateKey(privateKey);
1354
- const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1355
- const modulus2 = j.modulus;
1356
- if (modulus1.length != modulus2.length) {
1357
- return false;
1280
+ function exploreCertificate(certificate) {
1281
+ (0, import_node_assert4.default)(Buffer.isBuffer(certificate));
1282
+ const certificate_priv = certificate;
1283
+ if (!certificate_priv._exploreCertificate_cache) {
1284
+ const block_info = readTag(certificate, 0);
1285
+ const blocks = readStruct(certificate, block_info);
1286
+ certificate_priv._exploreCertificate_cache = {
1287
+ tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1288
+ signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1289
+ signatureValue: readSignatureValue(certificate, blocks[2])
1290
+ };
1358
1291
  }
1359
- return modulus1.toString("hex") === modulus2.toString("hex");
1292
+ return certificate_priv._exploreCertificate_cache;
1360
1293
  }
1361
- function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1362
- const initialBuffer = Buffer.from("Lorem Ipsum");
1363
- const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1364
- const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1365
- const finalString = decryptedBuffer.toString("utf-8");
1366
- return initialBuffer.toString("utf-8") === finalString;
1367
- }
1368
- function certificateMatchesPrivateKey(certificate, privateKey) {
1369
- const e = explorePrivateKey(privateKey);
1370
- const blockSize = e.modulus.length;
1371
- const certificatePEM = toPem(certificate, "CERTIFICATE");
1372
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1294
+ function split_der(certificateChain) {
1295
+ const certificate_chain = [];
1296
+ do {
1297
+ const block_info = readTag(certificateChain, 0);
1298
+ const length = block_info.position + block_info.length;
1299
+ const der_certificate = certificateChain.subarray(0, length);
1300
+ certificate_chain.push(der_certificate);
1301
+ certificateChain = certificateChain.subarray(length);
1302
+ } while (certificateChain.length > 0);
1303
+ return certificate_chain;
1373
1304
  }
1374
-
1375
- // source/common.ts
1376
- var import_crypto2 = __toESM(require("crypto"));
1377
- var KeyObjectOrig = import_crypto2.default.KeyObject;
1378
- var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_crypto2.default;
1379
- function isKeyObject(mayBeKeyObject) {
1380
- if (KeyObjectOrig) {
1381
- return mayBeKeyObject instanceof KeyObjectOrig;
1305
+ function combine_der(certificates) {
1306
+ for (const cert of certificates) {
1307
+ const b = split_der(cert);
1308
+ let sum = 0;
1309
+ b.forEach((block) => {
1310
+ const block_info = readTag(block, 0);
1311
+ (0, import_node_assert4.default)(block_info.position + block_info.length === block.length);
1312
+ sum += block.length;
1313
+ });
1314
+ (0, import_node_assert4.default)(sum === cert.length);
1382
1315
  }
1383
- return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1316
+ return Buffer.concat(certificates);
1384
1317
  }
1385
- var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1386
- CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1387
- CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1388
- CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1389
- CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1390
- return CertificatePurpose2;
1391
- })(CertificatePurpose || {});
1392
1318
 
1393
1319
  // source/crypto_utils2.ts
1394
- var import_assert5 = __toESM(require("assert"));
1320
+ var import_node_assert5 = __toESM(require("assert"));
1395
1321
  var import_jsrsasign2 = __toESM(require("jsrsasign"));
1396
1322
  function rsaLengthPrivateKey(key) {
1397
1323
  const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
@@ -1402,8 +1328,8 @@ function toPem2(raw_key, pem) {
1402
1328
  if (raw_key.hidden) {
1403
1329
  return toPem2(raw_key.hidden, pem);
1404
1330
  }
1405
- (0, import_assert5.default)(raw_key, "expecting a key");
1406
- (0, import_assert5.default)(typeof pem === "string");
1331
+ (0, import_node_assert5.default)(raw_key, "expecting a key");
1332
+ (0, import_node_assert5.default)(typeof pem === "string");
1407
1333
  if (isKeyObject(raw_key)) {
1408
1334
  const _raw_key = raw_key;
1409
1335
  if (pem === "RSA PRIVATE KEY") {
@@ -1423,40 +1349,40 @@ function coercePublicKeyPem(publicKey) {
1423
1349
  if (isKeyObject(publicKey)) {
1424
1350
  return publicKey.export({ format: "pem", type: "spki" }).toString();
1425
1351
  }
1426
- (0, import_assert5.default)(typeof publicKey === "string");
1352
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1427
1353
  return publicKey;
1428
1354
  }
1429
1355
  function coerceRsaPublicKeyPem(publicKey) {
1430
1356
  if (isKeyObject(publicKey)) {
1431
1357
  return publicKey.export({ format: "pem", type: "spki" }).toString();
1432
1358
  }
1433
- (0, import_assert5.default)(typeof publicKey === "string");
1359
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1434
1360
  return publicKey;
1435
1361
  }
1436
1362
  function rsaLengthPublicKey(key) {
1437
1363
  key = coercePublicKeyPem(key);
1438
- (0, import_assert5.default)(typeof key === "string");
1364
+ (0, import_node_assert5.default)(typeof key === "string");
1439
1365
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1440
1366
  return a.n.toString(16).length / 2;
1441
1367
  }
1442
1368
  function rsaLengthRsaPublicKey(key) {
1443
1369
  key = coerceRsaPublicKeyPem(key);
1444
- (0, import_assert5.default)(typeof key === "string");
1370
+ (0, import_node_assert5.default)(typeof key === "string");
1445
1371
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1446
1372
  return a.n.toString(16).length / 2;
1447
1373
  }
1448
1374
 
1449
1375
  // source/derived_keys.ts
1450
- var import_assert7 = __toESM(require("assert"));
1451
- var import_crypto3 = require("crypto");
1376
+ var import_node_assert7 = __toESM(require("assert"));
1377
+ var import_node_crypto3 = require("crypto");
1452
1378
 
1453
1379
  // source/explore_certificate.ts
1454
- var import_assert6 = __toESM(require("assert"));
1380
+ var import_node_assert6 = __toESM(require("assert"));
1455
1381
  function coerceCertificate(certificate) {
1456
1382
  if (typeof certificate === "string") {
1457
1383
  certificate = convertPEMtoDER(certificate);
1458
1384
  }
1459
- (0, import_assert6.default)(Buffer.isBuffer(certificate));
1385
+ (0, import_node_assert6.default)(Buffer.isBuffer(certificate));
1460
1386
  return certificate;
1461
1387
  }
1462
1388
  function exploreCertificateInfo(certificate) {
@@ -1470,21 +1396,21 @@ function exploreCertificateInfo(certificate) {
1470
1396
  subject: certInfo.tbsCertificate.subject
1471
1397
  };
1472
1398
  if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1473
- throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1399
+ throw new Error(`Invalid public key length (expecting 128,256,384 or 512): ${data.publicKeyLength}`);
1474
1400
  }
1475
1401
  return data;
1476
1402
  }
1477
1403
 
1478
1404
  // source/derived_keys.ts
1479
1405
  function HMAC_HASH(sha1or256, secret, message) {
1480
- return (0, import_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1406
+ return (0, import_node_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1481
1407
  }
1482
1408
  function plus(buf1, buf2) {
1483
1409
  return Buffer.concat([buf1, buf2]);
1484
1410
  }
1485
1411
  function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1486
- (0, import_assert7.default)(Buffer.isBuffer(seed));
1487
- (0, import_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1412
+ (0, import_node_assert7.default)(Buffer.isBuffer(seed));
1413
+ (0, import_node_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1488
1414
  const a = [];
1489
1415
  a[0] = seed;
1490
1416
  let index = 1;
@@ -1497,12 +1423,12 @@ function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1497
1423
  return p_hash.subarray(0, minLength);
1498
1424
  }
1499
1425
  function computeDerivedKeys(secret, seed, options) {
1500
- (0, import_assert7.default)(Number.isFinite(options.signatureLength));
1501
- (0, import_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1502
- (0, import_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1503
- (0, import_assert7.default)(typeof options.algorithm === "string");
1426
+ (0, import_node_assert7.default)(Number.isFinite(options.signatureLength));
1427
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1428
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1429
+ (0, import_node_assert7.default)(typeof options.algorithm === "string");
1504
1430
  options.sha1or256 = options.sha1or256 || "SHA1";
1505
- (0, import_assert7.default)(typeof options.sha1or256 === "string");
1431
+ (0, import_node_assert7.default)(typeof options.sha1or256 === "string");
1506
1432
  const offset1 = options.signingKeyLength;
1507
1433
  const offset2 = offset1 + options.encryptingKeyLength;
1508
1434
  const minLength = offset2 + options.encryptingBlockSize;
@@ -1527,7 +1453,7 @@ function removePadding(buffer) {
1527
1453
  return reduceLength(buffer, nbPaddingBytes);
1528
1454
  }
1529
1455
  function verifyChunkSignature(chunk, options) {
1530
- (0, import_assert7.default)(Buffer.isBuffer(chunk));
1456
+ (0, import_node_assert7.default)(Buffer.isBuffer(chunk));
1531
1457
  let signatureLength = options.signatureLength || 0;
1532
1458
  if (signatureLength === 0) {
1533
1459
  const cert = exploreCertificateInfo(options.publicKey);
@@ -1538,23 +1464,23 @@ function verifyChunkSignature(chunk, options) {
1538
1464
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1539
1465
  }
1540
1466
  function computePaddingFooter(buffer, derivedKeys) {
1541
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1467
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "encryptingBlockSize"));
1542
1468
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1543
1469
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1544
1470
  padding.fill(paddingSize);
1545
1471
  return padding;
1546
1472
  }
1547
1473
  function derivedKeys_algorithm(derivedKeys) {
1548
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1474
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "algorithm"));
1549
1475
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1550
- (0, import_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1476
+ (0, import_node_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1551
1477
  return algorithm;
1552
1478
  }
1553
1479
  function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
1554
1480
  const algorithm = derivedKeys_algorithm(derivedKeys);
1555
1481
  const key = derivedKeys.encryptingKey;
1556
1482
  const initVector = derivedKeys.initializationVector;
1557
- const cipher = (0, import_crypto3.createCipheriv)(algorithm, key, initVector);
1483
+ const cipher = (0, import_node_crypto3.createCipheriv)(algorithm, key, initVector);
1558
1484
  cipher.setAutoPadding(false);
1559
1485
  const encrypted_chunks = [];
1560
1486
  encrypted_chunks.push(cipher.update(buffer));
@@ -1565,7 +1491,7 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1565
1491
  const algorithm = derivedKeys_algorithm(derivedKeys);
1566
1492
  const key = derivedKeys.encryptingKey;
1567
1493
  const initVector = derivedKeys.initializationVector;
1568
- const cipher = (0, import_crypto3.createDecipheriv)(algorithm, key, initVector);
1494
+ const cipher = (0, import_node_crypto3.createDecipheriv)(algorithm, key, initVector);
1569
1495
  cipher.setAutoPadding(false);
1570
1496
  const decrypted_chunks = [];
1571
1497
  decrypted_chunks.push(cipher.update(buffer));
@@ -1573,12 +1499,12 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1573
1499
  return Buffer.concat(decrypted_chunks);
1574
1500
  }
1575
1501
  function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1576
- (0, import_assert7.default)(Buffer.isBuffer(message));
1577
- (0, import_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1578
- (0, import_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1579
- (0, import_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1580
- const signature = (0, import_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1581
- (0, import_assert7.default)(signature.length === derivedKeys.signatureLength);
1502
+ (0, import_node_assert7.default)(Buffer.isBuffer(message));
1503
+ (0, import_node_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1504
+ (0, import_node_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1505
+ (0, import_node_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1506
+ const signature = (0, import_node_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1507
+ (0, import_node_assert7.default)(signature.length === derivedKeys.signatureLength);
1582
1508
  return signature;
1583
1509
  }
1584
1510
  function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
@@ -1623,7 +1549,7 @@ function _readTbsCertList(buffer, blockInfo) {
1623
1549
  const blocks = readStruct(buffer, blockInfo);
1624
1550
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1625
1551
  if (hasOptionalVersion) {
1626
- const version = readIntegerValue(buffer, blocks[0]);
1552
+ const _version = readIntegerValue(buffer, blocks[0]);
1627
1553
  const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1628
1554
  const issuer = readNameForCrl(buffer, blocks[2]);
1629
1555
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[2])));
@@ -1642,7 +1568,7 @@ function _readTbsCertList(buffer, blockInfo) {
1642
1568
  });
1643
1569
  }
1644
1570
  }
1645
- const ext0 = findBlockAtIndex(blocks, 0);
1571
+ const _ext0 = findBlockAtIndex(blocks, 0);
1646
1572
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1647
1573
  } else {
1648
1574
  const signature = readAlgorithmIdentifier(buffer, blocks[0]);
@@ -1682,10 +1608,21 @@ function _readExtensionRequest(buffer) {
1682
1608
  const extensions = inner_blocks.map((block1) => readExtension(buffer, block1));
1683
1609
  const result = {};
1684
1610
  for (const e of extensions) {
1685
- result[e.identifier.name] = e.value;
1611
+ switch (e.identifier.name) {
1612
+ case "basicConstraints":
1613
+ result.basicConstraints = e.value;
1614
+ break;
1615
+ case "keyUsage":
1616
+ result.keyUsage = e.value;
1617
+ break;
1618
+ case "subjectAltName":
1619
+ result.subjectAltName = e.value;
1620
+ break;
1621
+ default:
1622
+ break;
1623
+ }
1686
1624
  }
1687
- const { basicConstraints, keyUsage, subjectAltName } = result;
1688
- return { basicConstraints, keyUsage, subjectAltName };
1625
+ return result;
1689
1626
  }
1690
1627
  function readCertificationRequestInfo(buffer, block) {
1691
1628
  const blocks = readStruct(buffer, block);
@@ -1713,16 +1650,117 @@ function exploreCertificateSigningRequest(crl) {
1713
1650
  return csrInfo;
1714
1651
  }
1715
1652
 
1653
+ // source/explore_private_key.ts
1654
+ function f(buffer, b) {
1655
+ return buffer.subarray(b.position + 1, b.position + b.length);
1656
+ }
1657
+ var doDebug2 = !!process.env.DEBUG;
1658
+ function explorePrivateKey(privateKey2) {
1659
+ const privateKey1 = privateKey2.hidden;
1660
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1661
+ const block_info = readTag(privateKey, 0);
1662
+ const blocks = readStruct(privateKey, block_info);
1663
+ if (blocks.length === 9) {
1664
+ const version2 = f(privateKey, blocks[0]);
1665
+ const modulus2 = f(privateKey, blocks[1]);
1666
+ const publicExponent2 = f(privateKey, blocks[2]);
1667
+ const privateExponent2 = f(privateKey, blocks[3]);
1668
+ const prime12 = f(privateKey, blocks[4]);
1669
+ const prime22 = f(privateKey, blocks[5]);
1670
+ const exponent12 = f(privateKey, blocks[6]);
1671
+ const exponent22 = f(privateKey, blocks[7]);
1672
+ return {
1673
+ version: version2,
1674
+ modulus: modulus2,
1675
+ publicExponent: publicExponent2,
1676
+ privateExponent: privateExponent2,
1677
+ prime1: prime12,
1678
+ prime2: prime22,
1679
+ exponent1: exponent12,
1680
+ exponent2: exponent22
1681
+ };
1682
+ }
1683
+ if (doDebug2) {
1684
+ console.log("-------------------- private key:");
1685
+ console.log(block_info);
1686
+ console.log(
1687
+ blocks.map((b2) => ({
1688
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1689
+ l: b2.length,
1690
+ p: b2.position,
1691
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1692
+ }))
1693
+ );
1694
+ }
1695
+ const b = blocks[2];
1696
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1697
+ const block_info1 = readTag(bb, 0);
1698
+ const blocks1 = readStruct(bb, block_info1);
1699
+ if (doDebug2) {
1700
+ console.log(
1701
+ blocks1.map((b2) => ({
1702
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1703
+ l: b2.length,
1704
+ p: b2.position,
1705
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1706
+ }))
1707
+ );
1708
+ }
1709
+ const version = f(bb, blocks1[0]);
1710
+ const modulus = f(bb, blocks1[1]);
1711
+ const publicExponent = f(bb, blocks1[2]);
1712
+ const privateExponent = f(bb, blocks1[3]);
1713
+ const prime1 = f(bb, blocks1[4]);
1714
+ const prime2 = f(bb, blocks1[5]);
1715
+ const exponent1 = f(bb, blocks1[6]);
1716
+ const exponent2 = f(bb, blocks1[7]);
1717
+ return {
1718
+ version,
1719
+ modulus,
1720
+ publicExponent,
1721
+ privateExponent,
1722
+ prime1,
1723
+ prime2,
1724
+ exponent1,
1725
+ exponent2
1726
+ };
1727
+ }
1728
+
1716
1729
  // source/make_private_key_from_pem.ts
1717
1730
  function makePrivateKeyFromPem(privateKeyInPem) {
1718
1731
  return { hidden: privateKeyInPem };
1719
1732
  }
1720
1733
 
1721
1734
  // source/make_private_key_thumbprint.ts
1722
- function makePrivateKeyThumbPrint(privateKey) {
1735
+ function makePrivateKeyThumbPrint(_privateKey) {
1723
1736
  return Buffer.alloc(0);
1724
1737
  }
1725
1738
 
1739
+ // source/public_private_match.ts
1740
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1741
+ const i = exploreCertificate(certificate);
1742
+ const j = explorePrivateKey(privateKey);
1743
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1744
+ const modulus2 = j.modulus;
1745
+ if (modulus1.length !== modulus2.length) {
1746
+ return false;
1747
+ }
1748
+ return modulus1.toString("hex") === modulus2.toString("hex");
1749
+ }
1750
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1751
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1752
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1753
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1754
+ const finalString = decryptedBuffer.toString("utf-8");
1755
+ return initialBuffer.toString("utf-8") === finalString;
1756
+ }
1757
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1758
+ const e = explorePrivateKey(privateKey);
1759
+ const blockSize = e.modulus.length;
1760
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1761
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1762
+ }
1763
+
1726
1764
  // source/subject.ts
1727
1765
  var _keys = {
1728
1766
  C: "country",
@@ -1765,11 +1803,11 @@ var Subject = class _Subject {
1765
1803
  }
1766
1804
  const s = element.split("=");
1767
1805
  if (s.length !== 2) {
1768
- throw new Error("invalid format for " + element);
1806
+ throw new Error(`invalid format for ${element}`);
1769
1807
  }
1770
1808
  const longName = _keys[s[0]];
1771
1809
  if (!longName) {
1772
- throw new Error("Invalid field found in subject name " + s[0]);
1810
+ throw new Error(`Invalid field found in subject name ${s[0]}`);
1773
1811
  }
1774
1812
  const value = s[1];
1775
1813
  options[longName] = unquote(Buffer.from(value, "ascii").toString("utf8"));
@@ -1779,25 +1817,25 @@ var Subject = class _Subject {
1779
1817
  toStringInternal(sep) {
1780
1818
  const tmp = [];
1781
1819
  if (this.country) {
1782
- tmp.push("C=" + enquoteIfNecessary(this.country));
1820
+ tmp.push(`C=${enquoteIfNecessary(this.country)}`);
1783
1821
  }
1784
1822
  if (this.state) {
1785
- tmp.push("ST=" + enquoteIfNecessary(this.state));
1823
+ tmp.push(`ST=${enquoteIfNecessary(this.state)}`);
1786
1824
  }
1787
1825
  if (this.locality) {
1788
- tmp.push("L=" + enquoteIfNecessary(this.locality));
1826
+ tmp.push(`L=${enquoteIfNecessary(this.locality)}`);
1789
1827
  }
1790
1828
  if (this.organization) {
1791
- tmp.push("O=" + enquoteIfNecessary(this.organization));
1829
+ tmp.push(`O=${enquoteIfNecessary(this.organization)}`);
1792
1830
  }
1793
1831
  if (this.organizationalUnit) {
1794
- tmp.push("OU=" + enquoteIfNecessary(this.organizationalUnit));
1832
+ tmp.push(`OU=${enquoteIfNecessary(this.organizationalUnit)}`);
1795
1833
  }
1796
1834
  if (this.commonName) {
1797
- tmp.push("CN=" + enquoteIfNecessary(this.commonName));
1835
+ tmp.push(`CN=${enquoteIfNecessary(this.commonName)}`);
1798
1836
  }
1799
1837
  if (this.domainComponent) {
1800
- tmp.push("DC=" + enquoteIfNecessary(this.domainComponent));
1838
+ tmp.push(`DC=${enquoteIfNecessary(this.domainComponent)}`);
1801
1839
  }
1802
1840
  return tmp.join(sep);
1803
1841
  }
@@ -1806,12 +1844,12 @@ var Subject = class _Subject {
1806
1844
  }
1807
1845
  toString() {
1808
1846
  const t2 = this.toStringForOPCUA();
1809
- return t2 ? "/" + t2 : t2;
1847
+ return t2 ? `/${t2}` : t2;
1810
1848
  }
1811
1849
  };
1812
1850
 
1813
1851
  // source/verify_certificate_signature.ts
1814
- var import_crypto4 = require("crypto");
1852
+ var import_node_crypto4 = require("crypto");
1815
1853
  function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1816
1854
  const block_info = readTag(certificateOrCrl, 0);
1817
1855
  const blocks = readStruct(certificateOrCrl, block_info);
@@ -1820,7 +1858,7 @@ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1820
1858
  const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
1821
1859
  const p = split_der(parentCertificate)[0];
1822
1860
  const certPem = toPem(p, "CERTIFICATE");
1823
- const verify = (0, import_crypto4.createVerify)(signatureAlgorithm.identifier);
1861
+ const verify = (0, import_node_crypto4.createVerify)(signatureAlgorithm.identifier);
1824
1862
  verify.update(bufferToBeSigned);
1825
1863
  verify.end();
1826
1864
  return verify.verify(certPem, signatureValue);
@@ -1836,8 +1874,8 @@ async function verifyCertificateChain(certificateChain) {
1836
1874
  const cert = certificateChain[index - 1];
1837
1875
  const certParent = certificateChain[index];
1838
1876
  const certParentInfo = exploreCertificate(certParent);
1839
- const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1840
- if (!keyUsage.keyCertSign) {
1877
+ const keyUsage = certParentInfo.tbsCertificate.extensions?.keyUsage;
1878
+ if (!keyUsage || !keyUsage.keyCertSign) {
1841
1879
  return {
1842
1880
  status: "BadCertificateIssuerUseNotAllowed",
1843
1881
  reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
@@ -1877,15 +1915,15 @@ async function verifyCertificateChain(certificateChain) {
1877
1915
  }
1878
1916
 
1879
1917
  // source/x509/_crypto.ts
1880
- var x509 = __toESM(require("@peculiar/x509"));
1918
+ var import_node_crypto5 = __toESM(require("crypto"));
1881
1919
  var import_webcrypto = require("@peculiar/webcrypto");
1882
- var import_crypto5 = __toESM(require("crypto"));
1920
+ var x509 = __toESM(require("@peculiar/x509"));
1883
1921
  var x5092 = __toESM(require("@peculiar/x509"));
1884
1922
  var doDebug3 = false;
1885
1923
  var _crypto;
1886
1924
  var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1887
1925
  if (typeof window === "undefined") {
1888
- _crypto = import_crypto5.default;
1926
+ _crypto = import_node_crypto5.default;
1889
1927
  if (!_crypto?.subtle || ignoreCrypto) {
1890
1928
  _crypto = new import_webcrypto.Crypto();
1891
1929
  doDebug3 && console.warn("using @peculiar/webcrypto");
@@ -1899,7 +1937,7 @@ if (typeof window === "undefined") {
1899
1937
  x509.cryptoProvider.set(crypto);
1900
1938
  }
1901
1939
  function getCrypto() {
1902
- return _crypto || crypto || require("crypto");
1940
+ return _crypto || crypto || import_node_crypto5.default;
1903
1941
  }
1904
1942
 
1905
1943
  // source/x509/create_key_pair.ts
@@ -1925,7 +1963,7 @@ async function privateKeyToPEM(privateKey) {
1925
1963
  }
1926
1964
  async function derToPrivateKey(privDer) {
1927
1965
  const crypto3 = getCrypto();
1928
- return await crypto3.subtle.importKey(
1966
+ const importedKey = await crypto3.subtle.importKey(
1929
1967
  "pkcs8",
1930
1968
  privDer,
1931
1969
  {
@@ -1944,6 +1982,7 @@ async function derToPrivateKey(privDer) {
1944
1982
  // "deriveBits"
1945
1983
  ]
1946
1984
  );
1985
+ return importedKey;
1947
1986
  }
1948
1987
  async function pemToPrivateKey(pem) {
1949
1988
  const privDer = x5092.PemConverter.decode(pem);
@@ -1961,24 +2000,46 @@ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1961
2000
  throw new Error("not implemented");
1962
2001
  }
1963
2002
  async function _coercePrivateKey(privateKey) {
1964
- const KeyObject4 = crypto2.KeyObject;
2003
+ const KeyObject = crypto2.KeyObject;
1965
2004
  if (Buffer.isBuffer(privateKey)) {
1966
2005
  const privateKey1 = await derToPrivateKey(privateKey);
1967
- return KeyObject4.from(privateKey1);
2006
+ return KeyObject.from(privateKey1);
1968
2007
  } else if (typeof privateKey === "string") {
1969
2008
  try {
1970
2009
  const privateKey1 = await pemToPrivateKey(privateKey);
1971
- return KeyObject4.from(privateKey1);
2010
+ return KeyObject.from(privateKey1);
1972
2011
  } catch (err) {
1973
2012
  doDebug4 && console.log(privateKey);
1974
2013
  throw err;
1975
2014
  }
1976
- } else if (privateKey instanceof KeyObject4) {
2015
+ } else if (isKeyObject(privateKey)) {
1977
2016
  return privateKey;
1978
2017
  }
1979
2018
  throw new Error("Invalid privateKey");
1980
2019
  }
1981
2020
 
2021
+ // source/x509/_build_public_key.ts
2022
+ async function buildPublicKey(privateKey) {
2023
+ const crypto3 = getCrypto();
2024
+ const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
2025
+ delete jwk.d;
2026
+ delete jwk.dp;
2027
+ delete jwk.dq;
2028
+ delete jwk.q;
2029
+ delete jwk.qi;
2030
+ jwk.key_ops = [
2031
+ "encrypt",
2032
+ "sign"
2033
+ // "wrapKey"
2034
+ ];
2035
+ const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
2036
+ // "encrypt",
2037
+ // "sign",
2038
+ // "wrapKey",
2039
+ ]);
2040
+ return publicKey;
2041
+ }
2042
+
1982
2043
  // source/x509/_get_attributes.ts
1983
2044
  var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1984
2045
  var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
@@ -1987,19 +2048,19 @@ function getAttributes(purpose) {
1987
2048
  let keyUsageExtension = [];
1988
2049
  let usages;
1989
2050
  let nsComment;
1990
- let extension;
2051
+ let _extension;
1991
2052
  switch (purpose) {
1992
2053
  case 1 /* ForCertificateAuthority */:
1993
- extension = "v3_ca";
2054
+ _extension = "v3_ca";
1994
2055
  basicConstraints = new x5092.BasicConstraintsExtension(true, void 0, false);
1995
2056
  usages = keyUsageCA;
1996
2057
  keyUsageExtension = [];
1997
2058
  nsComment = "Self-signed certificate for CA generated by Node-OPCUA Certificate utility V2";
1998
2059
  break;
1999
- case 2 /* ForApplication */:
2000
- case 3 /* ForUserAuthentication */:
2060
+ // case CertificatePurpose.ForApplication:
2061
+ // case CertificatePurpose.ForUserAuthentication:
2001
2062
  default:
2002
- extension = "v3_selfsigned";
2063
+ _extension = "v3_selfsigned";
2003
2064
  basicConstraints = new x5092.BasicConstraintsExtension(false, void 0, true);
2004
2065
  usages = keyUsageApplication;
2005
2066
  keyUsageExtension = [x5092.ExtendedKeyUsage.serverAuth, x5092.ExtendedKeyUsage.clientAuth];
@@ -2009,28 +2070,6 @@ function getAttributes(purpose) {
2009
2070
  return { nsComment, basicConstraints, keyUsageExtension, usages };
2010
2071
  }
2011
2072
 
2012
- // source/x509/_build_public_key.ts
2013
- async function buildPublicKey(privateKey) {
2014
- const crypto3 = getCrypto();
2015
- const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
2016
- delete jwk.d;
2017
- delete jwk.dp;
2018
- delete jwk.dq;
2019
- delete jwk.q;
2020
- delete jwk.qi;
2021
- jwk.key_ops = [
2022
- "encrypt",
2023
- "sign"
2024
- // "wrapKey"
2025
- ];
2026
- const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
2027
- // "encrypt",
2028
- // "sign",
2029
- // "wrapKey",
2030
- ]);
2031
- return publicKey;
2032
- }
2033
-
2034
2073
  // source/x509/create_certificate_signing_request.ts
2035
2074
  async function createCertificateSigningRequest({
2036
2075
  privateKey,
@@ -2054,9 +2093,15 @@ async function createCertificateSigningRequest({
2054
2093
  publicKey
2055
2094
  };
2056
2095
  const alternativeNameExtensions = [];
2057
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
2058
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
2059
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
2096
+ for (const d of dns ?? []) {
2097
+ alternativeNameExtensions.push({ type: "dns", value: d });
2098
+ }
2099
+ for (const d of ip ?? []) {
2100
+ alternativeNameExtensions.push({ type: "ip", value: d });
2101
+ }
2102
+ if (applicationUri) {
2103
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
2104
+ }
2060
2105
  const { basicConstraints, usages } = getAttributes(purpose);
2061
2106
  const s = new Subject(subject || "");
2062
2107
  const s1 = s.toStringInternal(", ");
@@ -6350,9 +6395,19 @@ async function createSelfSignedCertificate({
6350
6395
  }
6351
6396
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6352
6397
  const alternativeNameExtensions = [];
6353
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6354
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6355
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
6398
+ if (dns) {
6399
+ for (const d of dns) {
6400
+ alternativeNameExtensions.push({ type: "dns", value: d });
6401
+ }
6402
+ }
6403
+ if (ip) {
6404
+ for (const d of ip) {
6405
+ alternativeNameExtensions.push({ type: "ip", value: d });
6406
+ }
6407
+ }
6408
+ if (applicationUri) {
6409
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
6410
+ }
6356
6411
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6357
6412
  const s = new Subject(subject || "");
6358
6413
  const s1 = s.toStringInternal(", ");
@@ -6384,19 +6439,37 @@ async function createSelfSignedCertificate({
6384
6439
  // source/index_web.ts
6385
6440
  var asn1 = { readDirectoryName, readTag, readStruct, readAlgorithmIdentifier, readSignatureValueBin };
6386
6441
 
6387
- // source_nodejs/read.ts
6388
- var import_assert8 = __toESM(require("assert"));
6442
+ // source_nodejs/generate_private_key_filename.ts
6389
6443
  var import_node_fs = __toESM(require("fs"));
6444
+ var import_jsrsasign3 = __toESM(require("jsrsasign"));
6445
+ async function generatePrivateKeyFile(privateKeyFilename, modulusLength) {
6446
+ const keys = await generateKeyPair(modulusLength);
6447
+ const privateKeyPem = await privateKeyToPEM(keys.privateKey);
6448
+ await import_node_fs.default.promises.writeFile(privateKeyFilename, privateKeyPem.privPem, "utf-8");
6449
+ privateKeyPem.privPem = "";
6450
+ privateKeyPem.privDer = new ArrayBuffer(0);
6451
+ }
6452
+ async function generatePrivateKeyFileAlternate(privateKeyFilename, modulusLength) {
6453
+ const kp = import_jsrsasign3.default.KEYUTIL.generateKeypair("RSA", modulusLength);
6454
+ const prv = kp.prvKeyObj;
6455
+ const _pub = kp.pubKeyObj;
6456
+ const prvpem = import_jsrsasign3.default.KEYUTIL.getPEM(prv, "PKCS8PRV");
6457
+ await import_node_fs.default.promises.writeFile(privateKeyFilename, prvpem, "utf-8");
6458
+ }
6459
+
6460
+ // source_nodejs/read.ts
6461
+ var import_node_assert8 = __toESM(require("assert"));
6462
+ var import_node_crypto6 = require("crypto");
6463
+ var import_node_fs2 = __toESM(require("fs"));
6390
6464
  var import_node_path = __toESM(require("path"));
6391
- var import_crypto13 = require("crypto");
6392
6465
  var import_sshpk = __toESM(require("sshpk"));
6393
6466
  function _readPemFile(filename) {
6394
- (0, import_assert8.default)(typeof filename === "string");
6395
- return removeTrailingLF(import_node_fs.default.readFileSync(filename, "utf-8"));
6467
+ (0, import_node_assert8.default)(typeof filename === "string");
6468
+ return removeTrailingLF(import_node_fs2.default.readFileSync(filename, "utf-8"));
6396
6469
  }
6397
6470
  function _readPemOrDerFileAsDER(filename) {
6398
6471
  if (filename.match(/.*\.der/)) {
6399
- return import_node_fs.default.readFileSync(filename);
6472
+ return import_node_fs2.default.readFileSync(filename);
6400
6473
  }
6401
6474
  const raw_key = _readPemFile(filename);
6402
6475
  return convertPEMtoDER(raw_key);
@@ -6406,34 +6479,35 @@ function readCertificate(filename) {
6406
6479
  }
6407
6480
  function readPublicKey(filename) {
6408
6481
  if (filename.match(/.*\.der/)) {
6409
- const der = import_node_fs.default.readFileSync(filename);
6410
- return (0, import_crypto13.createPublicKey)(der);
6482
+ const der = import_node_fs2.default.readFileSync(filename);
6483
+ return (0, import_node_crypto6.createPublicKey)(der);
6411
6484
  } else {
6412
6485
  const raw_key = _readPemFile(filename);
6413
- return (0, import_crypto13.createPublicKey)(raw_key);
6486
+ return (0, import_node_crypto6.createPublicKey)(raw_key);
6414
6487
  }
6415
6488
  }
6416
6489
  function myCreatePrivateKey(rawKey) {
6417
- if (!import_crypto13.createPrivateKey || process.env.NO_CREATE_PRIVATEKEY) {
6490
+ if (!import_node_crypto6.createPrivateKey || process.env.NO_CREATE_PRIVATEKEY) {
6418
6491
  if (Buffer.isBuffer(rawKey)) {
6419
6492
  const pemKey = toPem(rawKey, "PRIVATE KEY");
6420
- (0, import_assert8.default)(["RSA PRIVATE KEY", "PRIVATE KEY"].indexOf(identifyPemType(pemKey)) >= 0);
6493
+ (0, import_node_assert8.default)(["RSA PRIVATE KEY", "PRIVATE KEY"].indexOf(identifyPemType(pemKey)) >= 0);
6421
6494
  return { hidden: pemKey };
6422
6495
  }
6423
6496
  return { hidden: ensureTrailingLF(rawKey) };
6424
6497
  }
6425
6498
  const backup = process.env.OPENSSL_CONF;
6426
6499
  process.env.OPENSSL_CONF = "/dev/null";
6427
- const retValue = (0, import_crypto13.createPrivateKey)(rawKey);
6500
+ const retValue = (0, import_node_crypto6.createPrivateKey)(rawKey);
6428
6501
  process.env.OPENSSL_CONF = backup;
6429
6502
  return { hidden: retValue };
6430
6503
  }
6431
6504
  function ensureTrailingLF(str) {
6432
- return str.match(/\n$/) ? str : str + "\n";
6505
+ return str.match(/\n$/) ? str : `${str}
6506
+ `;
6433
6507
  }
6434
6508
  function readPrivateKey(filename) {
6435
6509
  if (filename.match(/.*\.der/)) {
6436
- const der = import_node_fs.default.readFileSync(filename);
6510
+ const der = import_node_fs2.default.readFileSync(filename);
6437
6511
  return myCreatePrivateKey(der);
6438
6512
  } else {
6439
6513
  const raw_key = _readPemFile(filename);
@@ -6462,32 +6536,32 @@ function getCertificateStore() {
6462
6536
  return _g_certificate_store;
6463
6537
  }
6464
6538
  function readPrivateRsaKey(filename) {
6465
- if (!import_crypto13.createPrivateKey) {
6539
+ if (!import_node_crypto6.createPrivateKey) {
6466
6540
  throw new Error("createPrivateKey is not supported in this environment");
6467
6541
  }
6468
- if (filename.substring(0, 1) !== "." && !import_node_fs.default.existsSync(filename)) {
6542
+ if (filename.substring(0, 1) !== "." && !import_node_fs2.default.existsSync(filename)) {
6469
6543
  filename = import_node_path.default.join(getCertificateStore(), filename);
6470
6544
  }
6471
- const content = import_node_fs.default.readFileSync(filename, "utf8");
6545
+ const content = import_node_fs2.default.readFileSync(filename, "utf8");
6472
6546
  const sshKey = import_sshpk.default.parsePrivateKey(content, "auto");
6473
6547
  const key = sshKey.toString("pkcs1");
6474
- const hidden = (0, import_crypto13.createPrivateKey)({ format: "pem", type: "pkcs1", key });
6548
+ const hidden = (0, import_node_crypto6.createPrivateKey)({ format: "pem", type: "pkcs1", key });
6475
6549
  return { hidden };
6476
6550
  }
6477
6551
  function readPublicRsaKey(filename) {
6478
- if (filename.substring(0, 1) !== "." && !import_node_fs.default.existsSync(filename)) {
6552
+ if (filename.substring(0, 1) !== "." && !import_node_fs2.default.existsSync(filename)) {
6479
6553
  filename = import_node_path.default.join(getCertificateStore(), filename);
6480
6554
  }
6481
- const content = import_node_fs.default.readFileSync(filename, "utf-8");
6555
+ const content = import_node_fs2.default.readFileSync(filename, "utf-8");
6482
6556
  const sshKey = import_sshpk.default.parseKey(content, "ssh");
6483
6557
  const key = sshKey.toString("pkcs1");
6484
- return (0, import_crypto13.createPublicKey)({ format: "pem", type: "pkcs1", key });
6558
+ return (0, import_node_crypto6.createPublicKey)({ format: "pem", type: "pkcs1", key });
6485
6559
  }
6486
6560
 
6487
6561
  // source_nodejs/read_certificate_revocation_list.ts
6488
- var import_node_fs2 = __toESM(require("fs"));
6562
+ var import_node_fs3 = __toESM(require("fs"));
6489
6563
  async function readCertificateRevocationList(filename) {
6490
- const crl = await import_node_fs2.default.promises.readFile(filename);
6564
+ const crl = await import_node_fs3.default.promises.readFile(filename);
6491
6565
  if (crl[0] === 48 && crl[1] === 130) {
6492
6566
  return crl;
6493
6567
  }
@@ -6496,33 +6570,15 @@ async function readCertificateRevocationList(filename) {
6496
6570
  }
6497
6571
 
6498
6572
  // source_nodejs/read_certificate_signing_request.ts
6499
- var import_node_fs3 = __toESM(require("fs"));
6573
+ var import_node_fs4 = __toESM(require("fs"));
6500
6574
  async function readCertificateSigningRequest(filename) {
6501
- const csr = await import_node_fs3.default.promises.readFile(filename);
6575
+ const csr = await import_node_fs4.default.promises.readFile(filename);
6502
6576
  if (csr[0] === 48 && csr[1] === 130) {
6503
6577
  return csr;
6504
6578
  }
6505
6579
  const raw_crl = csr.toString();
6506
6580
  return convertPEMtoDER(raw_crl);
6507
6581
  }
6508
-
6509
- // source_nodejs/generate_private_key_filename.ts
6510
- var import_node_fs4 = __toESM(require("fs"));
6511
- var import_jsrsasign3 = __toESM(require("jsrsasign"));
6512
- async function generatePrivateKeyFile(privateKeyFilename, modulusLength) {
6513
- const keys = await generateKeyPair(modulusLength);
6514
- const privateKeyPem = await privateKeyToPEM(keys.privateKey);
6515
- await import_node_fs4.default.promises.writeFile(privateKeyFilename, privateKeyPem.privPem, "utf-8");
6516
- privateKeyPem.privPem = "";
6517
- privateKeyPem.privDer = new ArrayBuffer(0);
6518
- }
6519
- async function generatePrivateKeyFileAlternate(privateKeyFilename, modulusLength) {
6520
- const kp = import_jsrsasign3.default.KEYUTIL.generateKeypair("RSA", modulusLength);
6521
- const prv = kp.prvKeyObj;
6522
- const pub = kp.pubKeyObj;
6523
- const prvpem = import_jsrsasign3.default.KEYUTIL.getPEM(prv, "PKCS8PRV");
6524
- await import_node_fs4.default.promises.writeFile(privateKeyFilename, prvpem, "utf-8");
6525
- }
6526
6582
  // Annotate the CommonJS export names for ESM import in node:
6527
6583
  0 && (module.exports = {
6528
6584
  CertificatePurpose,