node-opcua-crypto 4.16.0 → 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.
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,374 +1251,73 @@ 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
- }
1041
- return {
1042
- version,
1043
- serialNumber,
1044
- signature,
1045
- issuer,
1046
- validity,
1047
- subject,
1048
- subjectFingerPrint,
1049
- subjectPublicKeyInfo,
1050
- extensions
1051
- };
1052
- }
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]);
1267
+ }
1338
1268
  return {
1339
- version,
1340
- modulus,
1341
- publicExponent,
1342
- privateExponent,
1343
- prime1,
1344
- prime2,
1345
- exponent1,
1346
- exponent2
1269
+ version: _version,
1270
+ serialNumber,
1271
+ signature,
1272
+ issuer,
1273
+ validity,
1274
+ subject,
1275
+ subjectFingerPrint,
1276
+ subjectPublicKeyInfo,
1277
+ extensions
1347
1278
  };
1348
1279
  }
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");
1360
- }
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;
1292
+ return certificate_priv._exploreCertificate_cache;
1367
1293
  }
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(", ");
@@ -2209,7 +2254,7 @@ var BufferSourceConverter = class _BufferSourceConverter {
2209
2254
  }
2210
2255
  };
2211
2256
  var STRING_TYPE = "string";
2212
- var HEX_REGEX = /^[0-9a-f]+$/i;
2257
+ var HEX_REGEX = /^[0-9a-f\s]+$/i;
2213
2258
  var BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2214
2259
  var BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
2215
2260
  var Utf8Converter = class {
@@ -2657,19 +2702,19 @@ var BIT_STRING_NAME = "BIT STRING";
2657
2702
  function HexBlock(BaseClass) {
2658
2703
  var _a2;
2659
2704
  return _a2 = class Some extends BaseClass {
2660
- constructor(...args) {
2661
- var _a3;
2662
- super(...args);
2663
- const params = args[0] || {};
2664
- this.isHexOnly = (_a3 = params.isHexOnly) !== null && _a3 !== void 0 ? _a3 : false;
2665
- this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2666
- }
2667
2705
  get valueHex() {
2668
2706
  return this.valueHexView.slice().buffer;
2669
2707
  }
2670
2708
  set valueHex(value) {
2671
2709
  this.valueHexView = new Uint8Array(value);
2672
2710
  }
2711
+ constructor(...args) {
2712
+ var _b;
2713
+ super(...args);
2714
+ const params = args[0] || {};
2715
+ this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false;
2716
+ this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2717
+ }
2673
2718
  fromBER(inputBuffer, inputOffset, inputLength) {
2674
2719
  const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
2675
2720
  if (!checkBufferParams(this, view, inputOffset, inputLength)) {
@@ -2704,12 +2749,6 @@ function HexBlock(BaseClass) {
2704
2749
  }, _a2.NAME = "hexBlock", _a2;
2705
2750
  }
2706
2751
  var LocalBaseBlock = class {
2707
- constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2708
- this.blockLength = blockLength;
2709
- this.error = error;
2710
- this.warnings = warnings;
2711
- this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2712
- }
2713
2752
  static blockName() {
2714
2753
  return this.NAME;
2715
2754
  }
@@ -2719,6 +2758,12 @@ var LocalBaseBlock = class {
2719
2758
  set valueBeforeDecode(value) {
2720
2759
  this.valueBeforeDecodeView = new Uint8Array(value);
2721
2760
  }
2761
+ constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2762
+ this.blockLength = blockLength;
2763
+ this.error = error;
2764
+ this.warnings = warnings;
2765
+ this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2766
+ }
2722
2767
  toJSON() {
2723
2768
  return {
2724
2769
  blockName: this.constructor.NAME,
@@ -2731,10 +2776,10 @@ var LocalBaseBlock = class {
2731
2776
  };
2732
2777
  LocalBaseBlock.NAME = "baseBlock";
2733
2778
  var ValueBlock = class extends LocalBaseBlock {
2734
- fromBER(inputBuffer, inputOffset, inputLength) {
2779
+ fromBER(_inputBuffer, _inputOffset, _inputLength) {
2735
2780
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2736
2781
  }
2737
- toBER(sizeOnly, writer) {
2782
+ toBER(_sizeOnly, _writer) {
2738
2783
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2739
2784
  }
2740
2785
  };
@@ -3075,7 +3120,9 @@ var BaseBlock = class extends LocalBaseBlock {
3075
3120
  return Convert.ToHex(this.toBER());
3076
3121
  }
3077
3122
  onAsciiEncoding() {
3078
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;
3123
+ const name = this.constructor.NAME;
3124
+ const value = Convert.ToHex(this.valueBlock.valueBeforeDecodeView);
3125
+ return `${name} : ${value}`;
3079
3126
  }
3080
3127
  isEqual(other) {
3081
3128
  if (this === other) {
@@ -3091,6 +3138,7 @@ var BaseBlock = class extends LocalBaseBlock {
3091
3138
  };
3092
3139
  BaseBlock.NAME = "BaseBlock";
3093
3140
  function prepareIndefiniteForm(baseBlock) {
3141
+ var _a2;
3094
3142
  if (baseBlock instanceof typeStore.Constructed) {
3095
3143
  for (const value of baseBlock.valueBlock.value) {
3096
3144
  if (prepareIndefiniteForm(value)) {
@@ -3098,21 +3146,21 @@ function prepareIndefiniteForm(baseBlock) {
3098
3146
  }
3099
3147
  }
3100
3148
  }
3101
- return !!baseBlock.lenBlock.isIndefiniteForm;
3149
+ return !!((_a2 = baseBlock.lenBlock) === null || _a2 === void 0 ? void 0 : _a2.isIndefiniteForm);
3102
3150
  }
3103
3151
  var BaseStringBlock = class extends BaseBlock {
3104
- constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3105
- super(parameters, stringValueBlockType);
3106
- if (value) {
3107
- this.fromString(value);
3108
- }
3109
- }
3110
3152
  getValue() {
3111
3153
  return this.valueBlock.value;
3112
3154
  }
3113
3155
  setValue(value) {
3114
3156
  this.valueBlock.value = value;
3115
3157
  }
3158
+ constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3159
+ super(parameters, stringValueBlockType);
3160
+ if (value) {
3161
+ this.fromString(value);
3162
+ }
3163
+ }
3116
3164
  fromBER(inputBuffer, inputOffset, inputLength) {
3117
3165
  const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
3118
3166
  if (resultOffset === -1) {
@@ -3471,10 +3519,10 @@ _a$v = Constructed;
3471
3519
  })();
3472
3520
  Constructed.NAME = "CONSTRUCTED";
3473
3521
  var LocalEndOfContentValueBlock = class extends ValueBlock {
3474
- fromBER(inputBuffer, inputOffset, inputLength) {
3522
+ fromBER(inputBuffer, inputOffset, _inputLength) {
3475
3523
  return inputOffset;
3476
3524
  }
3477
- toBER(sizeOnly) {
3525
+ toBER(_sizeOnly) {
3478
3526
  return EMPTY_BUFFER;
3479
3527
  }
3480
3528
  };
@@ -3535,17 +3583,6 @@ _a$t = Null;
3535
3583
  })();
3536
3584
  Null.NAME = "NULL";
3537
3585
  var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3538
- constructor({ value, ...parameters } = {}) {
3539
- super(parameters);
3540
- if (parameters.valueHex) {
3541
- this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3542
- } else {
3543
- this.valueHexView = new Uint8Array(1);
3544
- }
3545
- if (value) {
3546
- this.value = value;
3547
- }
3548
- }
3549
3586
  get value() {
3550
3587
  for (const octet of this.valueHexView) {
3551
3588
  if (octet > 0) {
@@ -3557,6 +3594,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3557
3594
  set value(value) {
3558
3595
  this.valueHexView[0] = value ? 255 : 0;
3559
3596
  }
3597
+ constructor({ value, ...parameters } = {}) {
3598
+ super(parameters);
3599
+ if (parameters.valueHex) {
3600
+ this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3601
+ } else {
3602
+ this.valueHexView = new Uint8Array(1);
3603
+ }
3604
+ if (value) {
3605
+ this.value = value;
3606
+ }
3607
+ }
3560
3608
  fromBER(inputBuffer, inputOffset, inputLength) {
3561
3609
  const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
3562
3610
  if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
@@ -3583,17 +3631,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3583
3631
  LocalBooleanValueBlock.NAME = "BooleanValueBlock";
3584
3632
  var _a$s;
3585
3633
  var Boolean = class extends BaseBlock {
3586
- constructor(parameters = {}) {
3587
- super(parameters, LocalBooleanValueBlock);
3588
- this.idBlock.tagClass = 1;
3589
- this.idBlock.tagNumber = 1;
3590
- }
3591
3634
  getValue() {
3592
3635
  return this.valueBlock.value;
3593
3636
  }
3594
3637
  setValue(value) {
3595
3638
  this.valueBlock.value = value;
3596
3639
  }
3640
+ constructor(parameters = {}) {
3641
+ super(parameters, LocalBooleanValueBlock);
3642
+ this.idBlock.tagClass = 1;
3643
+ this.idBlock.tagNumber = 1;
3644
+ }
3597
3645
  onAsciiEncoding() {
3598
3646
  return `${this.constructor.NAME} : ${this.getValue}`;
3599
3647
  }
@@ -3651,7 +3699,7 @@ var LocalOctetStringValueBlock = class extends HexBlock(LocalConstructedValueBlo
3651
3699
  };
3652
3700
  LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
3653
3701
  var _a$r;
3654
- var OctetString = class _OctetString extends BaseBlock {
3702
+ var OctetString = class extends BaseBlock {
3655
3703
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
3656
3704
  var _b, _c;
3657
3705
  (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length);
@@ -3689,7 +3737,7 @@ var OctetString = class _OctetString extends BaseBlock {
3689
3737
  this.valueBlock.value = [asn.result];
3690
3738
  }
3691
3739
  }
3692
- } catch (e) {
3740
+ } catch {
3693
3741
  }
3694
3742
  }
3695
3743
  return super.fromBER(inputBuffer, inputOffset, inputLength);
@@ -3698,7 +3746,9 @@ var OctetString = class _OctetString extends BaseBlock {
3698
3746
  if (this.valueBlock.isConstructed || this.valueBlock.value && this.valueBlock.value.length) {
3699
3747
  return Constructed.prototype.onAsciiEncoding.call(this);
3700
3748
  }
3701
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueHexView)}`;
3749
+ const name = this.constructor.NAME;
3750
+ const value = Convert.ToHex(this.valueBlock.valueHexView);
3751
+ return `${name} : ${value}`;
3702
3752
  }
3703
3753
  getValue() {
3704
3754
  if (!this.idBlock.isConstructed) {
@@ -3706,7 +3756,7 @@ var OctetString = class _OctetString extends BaseBlock {
3706
3756
  }
3707
3757
  const array = [];
3708
3758
  for (const content of this.valueBlock.value) {
3709
- if (content instanceof _OctetString) {
3759
+ if (content instanceof _a$r) {
3710
3760
  array.push(content.valueBlock.valueHexView);
3711
3761
  }
3712
3762
  }
@@ -3776,7 +3826,7 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3776
3826
  this.value = [asn.result];
3777
3827
  }
3778
3828
  }
3779
- } catch (e) {
3829
+ } catch {
3780
3830
  }
3781
3831
  }
3782
3832
  this.valueHexView = intBuffer.subarray(1);
@@ -3791,7 +3841,9 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3791
3841
  return new ArrayBuffer(this.valueHexView.byteLength + 1);
3792
3842
  }
3793
3843
  if (!this.valueHexView.byteLength) {
3794
- return EMPTY_BUFFER;
3844
+ const empty = new Uint8Array(1);
3845
+ empty[0] = 0;
3846
+ return empty.buffer;
3795
3847
  }
3796
3848
  const retView = new Uint8Array(this.valueHexView.length + 1);
3797
3849
  retView[0] = this.unusedBits;
@@ -3841,7 +3893,9 @@ var BitString = class extends BaseBlock {
3841
3893
  bits.push(byte.toString(2).padStart(8, "0"));
3842
3894
  }
3843
3895
  const bitsStr = bits.join("");
3844
- return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;
3896
+ const name = this.constructor.NAME;
3897
+ const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits);
3898
+ return `${name} : ${value}`;
3845
3899
  }
3846
3900
  }
3847
3901
  };
@@ -3938,16 +3992,6 @@ function viewSub(first, second) {
3938
3992
  return firstViewCopy.slice();
3939
3993
  }
3940
3994
  var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3941
- constructor({ value, ...parameters } = {}) {
3942
- super(parameters);
3943
- this._valueDec = 0;
3944
- if (parameters.valueHex) {
3945
- this.setValueHex();
3946
- }
3947
- if (value !== void 0) {
3948
- this.valueDec = value;
3949
- }
3950
- }
3951
3995
  setValueHex() {
3952
3996
  if (this.valueHexView.length >= 4) {
3953
3997
  this.warnings.push("Too big Integer for decoding, hex only");
@@ -3960,6 +4004,16 @@ var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3960
4004
  }
3961
4005
  }
3962
4006
  }
4007
+ constructor({ value, ...parameters } = {}) {
4008
+ super(parameters);
4009
+ this._valueDec = 0;
4010
+ if (parameters.valueHex) {
4011
+ this.setValueHex();
4012
+ }
4013
+ if (value !== void 0) {
4014
+ this.valueDec = value;
4015
+ }
4016
+ }
3963
4017
  set valueDec(v) {
3964
4018
  this._valueDec = v;
3965
4019
  this.isHexOnly = false;
@@ -4072,7 +4126,7 @@ LocalIntegerValueBlock.NAME = "IntegerValueBlock";
4072
4126
  });
4073
4127
  })();
4074
4128
  var _a$o;
4075
- var Integer = class _Integer extends BaseBlock {
4129
+ var Integer = class extends BaseBlock {
4076
4130
  constructor(parameters = {}) {
4077
4131
  super(parameters, LocalIntegerValueBlock);
4078
4132
  this.idBlock.tagClass = 1;
@@ -4102,18 +4156,16 @@ var Integer = class _Integer extends BaseBlock {
4102
4156
  }
4103
4157
  writer.write(view);
4104
4158
  }
4105
- const res = new _Integer({
4106
- valueHex: writer.final()
4107
- });
4159
+ const res = new _a$o({ valueHex: writer.final() });
4108
4160
  return res;
4109
4161
  }
4110
4162
  convertToDER() {
4111
- const integer = new _Integer({ valueHex: this.valueBlock.valueHexView });
4163
+ const integer = new _a$o({ valueHex: this.valueBlock.valueHexView });
4112
4164
  integer.valueBlock.toDER();
4113
4165
  return integer;
4114
4166
  }
4115
4167
  convertFromDER() {
4116
- return new _Integer({
4168
+ return new _a$o({
4117
4169
  valueHex: this.valueBlock.valueHexView[0] === 0 ? this.valueBlock.valueHexView.subarray(1) : this.valueBlock.valueHexView
4118
4170
  });
4119
4171
  }
@@ -4376,17 +4428,17 @@ var LocalObjectIdentifierValueBlock = class extends ValueBlock {
4376
4428
  LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
4377
4429
  var _a$m;
4378
4430
  var ObjectIdentifier = class extends BaseBlock {
4379
- constructor(parameters = {}) {
4380
- super(parameters, LocalObjectIdentifierValueBlock);
4381
- this.idBlock.tagClass = 1;
4382
- this.idBlock.tagNumber = 6;
4383
- }
4384
4431
  getValue() {
4385
4432
  return this.valueBlock.toString();
4386
4433
  }
4387
4434
  setValue(value) {
4388
4435
  this.valueBlock.fromString(value);
4389
4436
  }
4437
+ constructor(parameters = {}) {
4438
+ super(parameters, LocalObjectIdentifierValueBlock);
4439
+ this.idBlock.tagClass = 1;
4440
+ this.idBlock.tagNumber = 6;
4441
+ }
4390
4442
  onAsciiEncoding() {
4391
4443
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4392
4444
  }
@@ -4506,7 +4558,7 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4506
4558
  }
4507
4559
  return resultOffset;
4508
4560
  }
4509
- toBER(sizeOnly, writer) {
4561
+ toBER(sizeOnly, _writer) {
4510
4562
  const retBuffers = [];
4511
4563
  for (let i = 0; i < this.value.length; i++) {
4512
4564
  const valueBuf = this.value[i].toBER(sizeOnly);
@@ -4568,17 +4620,17 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4568
4620
  LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
4569
4621
  var _a$l;
4570
4622
  var RelativeObjectIdentifier = class extends BaseBlock {
4571
- constructor(parameters = {}) {
4572
- super(parameters, LocalRelativeObjectIdentifierValueBlock);
4573
- this.idBlock.tagClass = 1;
4574
- this.idBlock.tagNumber = 13;
4575
- }
4576
4623
  getValue() {
4577
4624
  return this.valueBlock.toString();
4578
4625
  }
4579
4626
  setValue(value) {
4580
4627
  this.valueBlock.fromString(value);
4581
4628
  }
4629
+ constructor(parameters = {}) {
4630
+ super(parameters, LocalRelativeObjectIdentifierValueBlock);
4631
+ this.idBlock.tagClass = 1;
4632
+ this.idBlock.tagNumber = 13;
4633
+ }
4582
4634
  onAsciiEncoding() {
4583
4635
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4584
4636
  }
@@ -4975,7 +5027,8 @@ var GeneralizedTime = class extends UTCTime {
4975
5027
  this.millisecond = inputDate.getUTCMilliseconds();
4976
5028
  }
4977
5029
  toDate() {
4978
- return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond));
5030
+ const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond);
5031
+ return new Date(utcDate);
4979
5032
  }
4980
5033
  fromString(inputString) {
4981
5034
  let isUTC = false;
@@ -5224,28 +5277,28 @@ var Repeated = class extends Any {
5224
5277
  }
5225
5278
  };
5226
5279
  var RawData = class {
5227
- constructor({ data = EMPTY_VIEW } = {}) {
5228
- this.dataView = BufferSourceConverter.toUint8Array(data);
5229
- }
5230
5280
  get data() {
5231
5281
  return this.dataView.slice().buffer;
5232
5282
  }
5233
5283
  set data(value) {
5234
5284
  this.dataView = BufferSourceConverter.toUint8Array(value);
5235
5285
  }
5286
+ constructor({ data = EMPTY_VIEW } = {}) {
5287
+ this.dataView = BufferSourceConverter.toUint8Array(data);
5288
+ }
5236
5289
  fromBER(inputBuffer, inputOffset, inputLength) {
5237
5290
  const endLength = inputOffset + inputLength;
5238
5291
  this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
5239
5292
  return endLength;
5240
5293
  }
5241
- toBER(sizeOnly) {
5294
+ toBER(_sizeOnly) {
5242
5295
  return this.dataView.slice().buffer;
5243
5296
  }
5244
5297
  };
5245
5298
  function compareSchema(root, inputData, inputSchema) {
5246
5299
  if (inputSchema instanceof Choice) {
5247
- for (let j = 0; j < inputSchema.value.length; j++) {
5248
- const result = compareSchema(root, inputData, inputSchema.value[j]);
5300
+ for (const element of inputSchema.value) {
5301
+ const result = compareSchema(root, inputData, element);
5249
5302
  if (result.verified) {
5250
5303
  return {
5251
5304
  verified: true,
@@ -5256,9 +5309,7 @@ function compareSchema(root, inputData, inputSchema) {
5256
5309
  {
5257
5310
  const _result = {
5258
5311
  verified: false,
5259
- result: {
5260
- error: "Wrong values for Choice type"
5261
- }
5312
+ result: { error: "Wrong values for Choice type" }
5262
5313
  };
5263
5314
  if (inputSchema.hasOwnProperty(NAME))
5264
5315
  _result.name = inputSchema.name;
@@ -5404,9 +5455,7 @@ function compareSchema(root, inputData, inputSchema) {
5404
5455
  let admission = 0;
5405
5456
  let result = {
5406
5457
  verified: false,
5407
- result: {
5408
- error: "Unknown error"
5409
- }
5458
+ result: { error: "Unknown error" }
5410
5459
  };
5411
5460
  let maxLength = inputSchema.valueBlock.value.length;
5412
5461
  if (maxLength > 0) {
@@ -5783,10 +5832,7 @@ var AsnSchemaStorage = class {
5783
5832
  }
5784
5833
  }
5785
5834
  createDefault(target) {
5786
- const schema = {
5787
- type: AsnTypeTypes.Sequence,
5788
- items: {}
5789
- };
5835
+ const schema = { type: AsnTypeTypes.Sequence, items: {} };
5790
5836
  const parentSchema = this.findParentSchema(target);
5791
5837
  if (parentSchema) {
5792
5838
  Object.assign(schema, parentSchema);
@@ -5828,26 +5874,14 @@ var AsnSchemaStorage = class {
5828
5874
  const Container = item.repeated === "set" ? Set : Sequence;
5829
5875
  asn1Item = new Container({
5830
5876
  name: "",
5831
- value: [
5832
- new Repeated({
5833
- name,
5834
- value: asn1Item
5835
- })
5836
- ]
5877
+ value: [new Repeated({ name, value: asn1Item })]
5837
5878
  });
5838
5879
  }
5839
5880
  if (item.context !== null && item.context !== void 0) {
5840
5881
  if (item.implicit) {
5841
5882
  if (typeof item.type === "number" || isConvertible(item.type)) {
5842
5883
  const Container = item.repeated ? Constructed : Primitive;
5843
- asn1Value.push(new Container({
5844
- name,
5845
- optional,
5846
- idBlock: {
5847
- tagClass: 3,
5848
- tagNumber: item.context
5849
- }
5850
- }));
5884
+ asn1Value.push(new Container({ name, optional, idBlock: { tagClass: 3, tagNumber: item.context } }));
5851
5885
  } else {
5852
5886
  this.cache(item.type);
5853
5887
  const isRepeated = !!item.repeated;
@@ -5856,20 +5890,14 @@ var AsnSchemaStorage = class {
5856
5890
  asn1Value.push(new Constructed({
5857
5891
  name: !isRepeated ? name : "",
5858
5892
  optional,
5859
- idBlock: {
5860
- tagClass: 3,
5861
- tagNumber: item.context
5862
- },
5893
+ idBlock: { tagClass: 3, tagNumber: item.context },
5863
5894
  value
5864
5895
  }));
5865
5896
  }
5866
5897
  } else {
5867
5898
  asn1Value.push(new Constructed({
5868
5899
  optional,
5869
- idBlock: {
5870
- tagClass: 3,
5871
- tagNumber: item.context
5872
- },
5900
+ idBlock: { tagClass: 3, tagNumber: item.context },
5873
5901
  value: [asn1Item]
5874
5902
  }));
5875
5903
  }
@@ -5925,7 +5953,6 @@ var AsnParser = class {
5925
5953
  return res;
5926
5954
  }
5927
5955
  static fromASN(asn1Schema, target) {
5928
- var _a2;
5929
5956
  try {
5930
5957
  if (isConvertible(target)) {
5931
5958
  const value = new target();
@@ -5934,104 +5961,259 @@ var AsnParser = class {
5934
5961
  const schema = schemaStorage.get(target);
5935
5962
  schemaStorage.cache(target);
5936
5963
  let targetSchema = schema.schema;
5937
- if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
5938
- targetSchema = new Constructed({
5939
- idBlock: {
5940
- tagClass: 3,
5941
- tagNumber: asn1Schema.idBlock.tagNumber
5942
- },
5943
- value: schema.schema.valueBlock.value
5944
- });
5945
- for (const key in schema.items) {
5946
- delete asn1Schema[key];
5947
- }
5964
+ const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema);
5965
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.result) {
5966
+ return choiceResult.result;
5948
5967
  }
5949
- const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
5950
- if (!asn1ComparedSchema.verified) {
5951
- throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`);
5968
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.targetSchema) {
5969
+ targetSchema = choiceResult.targetSchema;
5952
5970
  }
5971
+ const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
5953
5972
  const res = new target();
5954
5973
  if (isTypeOfArray(target)) {
5955
- if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
5956
- throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
5957
- }
5958
- const itemType = schema.itemType;
5959
- if (typeof itemType === "number") {
5960
- const converter = defaultConverter(itemType);
5961
- if (!converter) {
5962
- throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
5963
- }
5964
- return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
5965
- } else {
5966
- return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
5967
- }
5974
+ return this.handleArrayTypes(asn1Schema, schema, target);
5975
+ }
5976
+ this.processSchemaItems(schema, sequenceResult, res);
5977
+ return res;
5978
+ } catch (error) {
5979
+ if (error instanceof AsnSchemaValidationError) {
5980
+ error.schemas.push(target.name);
5968
5981
  }
5982
+ throw error;
5983
+ }
5984
+ }
5985
+ static handleChoiceTypes(asn1Schema, schema, target, targetSchema) {
5986
+ if (asn1Schema.constructor === Constructed && schema.type === AsnTypeTypes.Choice && asn1Schema.idBlock.tagClass === 3) {
5969
5987
  for (const key in schema.items) {
5970
- const asn1SchemaValue = asn1ComparedSchema.result[key];
5971
- if (!asn1SchemaValue) {
5972
- continue;
5973
- }
5974
5988
  const schemaItem = schema.items[key];
5975
- const schemaItemType = schemaItem.type;
5976
- if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
5977
- const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
5978
- if (!converter) {
5979
- throw new Error("Converter is empty");
5980
- }
5981
- if (schemaItem.repeated) {
5982
- if (schemaItem.implicit) {
5983
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
5984
- const newItem = new Container();
5985
- newItem.valueBlock = asn1SchemaValue.valueBlock;
5986
- const newItemAsn = fromBER(newItem.toBER(false));
5987
- if (newItemAsn.offset === -1) {
5988
- throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
5989
+ if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
5990
+ if (typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type)) {
5991
+ const fieldSchema = schemaStorage.get(schemaItem.type);
5992
+ if (fieldSchema && fieldSchema.type === AsnTypeTypes.Sequence) {
5993
+ const newSeq = new Sequence();
5994
+ if ("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value) && "value" in newSeq.valueBlock) {
5995
+ newSeq.valueBlock.value = asn1Schema.valueBlock.value;
5996
+ const fieldValue = this.fromASN(newSeq, schemaItem.type);
5997
+ const res = new target();
5998
+ res[key] = fieldValue;
5999
+ return { result: res };
5989
6000
  }
5990
- if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
5991
- throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
5992
- }
5993
- const value = newItemAsn.result.valueBlock.value;
5994
- res[key] = Array.from(value, (element) => converter.fromASN(element));
5995
- } else {
5996
- res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
5997
- }
5998
- } else {
5999
- let value = asn1SchemaValue;
6000
- if (schemaItem.implicit) {
6001
- let newItem;
6002
- if (isConvertible(schemaItemType)) {
6003
- newItem = new schemaItemType().toSchema("");
6004
- } else {
6005
- const Asn1TypeName = AsnPropTypes[schemaItemType];
6006
- const Asn1Type = index_es_exports[Asn1TypeName];
6007
- if (!Asn1Type) {
6008
- throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
6009
- }
6010
- newItem = new Asn1Type();
6011
- }
6012
- newItem.valueBlock = value.valueBlock;
6013
- value = fromBER(newItem.toBER(false)).result;
6014
6001
  }
6015
- res[key] = converter.fromASN(value);
6016
6002
  }
6017
- } else {
6018
- if (schemaItem.repeated) {
6019
- if (!Array.isArray(asn1SchemaValue)) {
6020
- throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
6021
- }
6022
- res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
6023
- } else {
6024
- res[key] = this.fromASN(asn1SchemaValue, schemaItemType);
6003
+ }
6004
+ }
6005
+ } else if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
6006
+ const newTargetSchema = new Constructed({
6007
+ idBlock: {
6008
+ tagClass: 3,
6009
+ tagNumber: asn1Schema.idBlock.tagNumber
6010
+ },
6011
+ value: schema.schema.valueBlock.value
6012
+ });
6013
+ for (const key in schema.items) {
6014
+ delete asn1Schema[key];
6015
+ }
6016
+ return { targetSchema: newTargetSchema };
6017
+ }
6018
+ return null;
6019
+ }
6020
+ static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
6021
+ if (schema.type === AsnTypeTypes.Sequence) {
6022
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
6023
+ if (!asn1ComparedSchema.verified) {
6024
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
6025
+ }
6026
+ return asn1ComparedSchema;
6027
+ } else {
6028
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
6029
+ if (!asn1ComparedSchema.verified) {
6030
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
6031
+ }
6032
+ return asn1ComparedSchema;
6033
+ }
6034
+ }
6035
+ static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
6036
+ let elementsToProcess = asn1Elements.slice(asn1Index);
6037
+ if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
6038
+ const seq = elementsToProcess[0];
6039
+ if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
6040
+ elementsToProcess = seq.valueBlock.value;
6041
+ }
6042
+ }
6043
+ if (typeof schemaItem.type === "number") {
6044
+ const converter = defaultConverter(schemaItem.type);
6045
+ if (!converter)
6046
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
6047
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
6048
+ try {
6049
+ return converter.fromASN(el);
6050
+ } catch {
6051
+ return void 0;
6052
+ }
6053
+ }).filter((v) => v !== void 0);
6054
+ } else {
6055
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
6056
+ try {
6057
+ return this.fromASN(el, schemaItem.type);
6058
+ } catch {
6059
+ return void 0;
6060
+ }
6061
+ }).filter((v) => v !== void 0);
6062
+ }
6063
+ }
6064
+ static processPrimitiveField(asn1Element, schemaItem) {
6065
+ const converter = defaultConverter(schemaItem.type);
6066
+ if (!converter)
6067
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
6068
+ return converter.fromASN(asn1Element);
6069
+ }
6070
+ static isOptionalChoiceField(schemaItem) {
6071
+ return schemaItem.optional && typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type) && schemaStorage.get(schemaItem.type).type === AsnTypeTypes.Choice;
6072
+ }
6073
+ static processOptionalChoiceField(asn1Element, schemaItem) {
6074
+ try {
6075
+ const value = this.fromASN(asn1Element, schemaItem.type);
6076
+ return { processed: true, value };
6077
+ } catch (err) {
6078
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
6079
+ return { processed: false };
6080
+ }
6081
+ throw err;
6082
+ }
6083
+ }
6084
+ static handleArrayTypes(asn1Schema, schema, target) {
6085
+ if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
6086
+ throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
6087
+ }
6088
+ const itemType = schema.itemType;
6089
+ if (typeof itemType === "number") {
6090
+ const converter = defaultConverter(itemType);
6091
+ if (!converter) {
6092
+ throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
6093
+ }
6094
+ return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
6095
+ } else {
6096
+ return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
6097
+ }
6098
+ }
6099
+ static processSchemaItems(schema, asn1ComparedSchema, res) {
6100
+ for (const key in schema.items) {
6101
+ const asn1SchemaValue = asn1ComparedSchema.result[key];
6102
+ if (!asn1SchemaValue) {
6103
+ continue;
6104
+ }
6105
+ const schemaItem = schema.items[key];
6106
+ const schemaItemType = schemaItem.type;
6107
+ let parsedValue;
6108
+ if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
6109
+ parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6110
+ } else {
6111
+ parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6112
+ }
6113
+ if (parsedValue && typeof parsedValue === "object" && "value" in parsedValue && "raw" in parsedValue) {
6114
+ res[key] = parsedValue.value;
6115
+ res[`${key}Raw`] = parsedValue.raw;
6116
+ } else {
6117
+ res[key] = parsedValue;
6118
+ }
6119
+ }
6120
+ }
6121
+ static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6122
+ var _a2;
6123
+ const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
6124
+ if (!converter) {
6125
+ throw new Error("Converter is empty");
6126
+ }
6127
+ if (schemaItem.repeated) {
6128
+ return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter);
6129
+ } else {
6130
+ return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter);
6131
+ }
6132
+ }
6133
+ static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter) {
6134
+ if (schemaItem.implicit) {
6135
+ const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
6136
+ const newItem = new Container();
6137
+ newItem.valueBlock = asn1SchemaValue.valueBlock;
6138
+ const newItemAsn = fromBER(newItem.toBER(false));
6139
+ if (newItemAsn.offset === -1) {
6140
+ throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
6141
+ }
6142
+ if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
6143
+ throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
6144
+ }
6145
+ const value = newItemAsn.result.valueBlock.value;
6146
+ return Array.from(value, (element) => converter.fromASN(element));
6147
+ } else {
6148
+ return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
6149
+ }
6150
+ }
6151
+ static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter) {
6152
+ let value = asn1SchemaValue;
6153
+ if (schemaItem.implicit) {
6154
+ let newItem;
6155
+ if (isConvertible(schemaItemType)) {
6156
+ newItem = new schemaItemType().toSchema("");
6157
+ } else {
6158
+ const Asn1TypeName = AsnPropTypes[schemaItemType];
6159
+ const Asn1Type = index_es_exports[Asn1TypeName];
6160
+ if (!Asn1Type) {
6161
+ throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
6162
+ }
6163
+ newItem = new Asn1Type();
6164
+ }
6165
+ newItem.valueBlock = value.valueBlock;
6166
+ value = fromBER(newItem.toBER(false)).result;
6167
+ }
6168
+ return converter.fromASN(value);
6169
+ }
6170
+ static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6171
+ if (schemaItem.repeated) {
6172
+ if (!Array.isArray(asn1SchemaValue)) {
6173
+ throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
6174
+ }
6175
+ return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
6176
+ } else {
6177
+ const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
6178
+ if (this.isOptionalChoiceField(schemaItem)) {
6179
+ try {
6180
+ return this.fromASN(valueToProcess, schemaItemType);
6181
+ } catch (err) {
6182
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
6183
+ return void 0;
6025
6184
  }
6185
+ throw err;
6186
+ }
6187
+ } else {
6188
+ const parsedValue = this.fromASN(valueToProcess, schemaItemType);
6189
+ if (schemaItem.raw) {
6190
+ return {
6191
+ value: parsedValue,
6192
+ raw: asn1SchemaValue.valueBeforeDecodeView
6193
+ };
6026
6194
  }
6195
+ return parsedValue;
6027
6196
  }
6028
- return res;
6029
- } catch (error) {
6030
- if (error instanceof AsnSchemaValidationError) {
6031
- error.schemas.push(target.name);
6197
+ }
6198
+ }
6199
+ static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
6200
+ if (schemaItem.implicit && typeof schemaItem.context === "number") {
6201
+ const schema = schemaStorage.get(schemaItemType);
6202
+ if (schema.type === AsnTypeTypes.Sequence) {
6203
+ const newSeq = new Sequence();
6204
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSeq.valueBlock) {
6205
+ newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
6206
+ return newSeq;
6207
+ }
6208
+ } else if (schema.type === AsnTypeTypes.Set) {
6209
+ const newSet = new Set();
6210
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSet.valueBlock) {
6211
+ newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
6212
+ return newSet;
6213
+ }
6032
6214
  }
6033
- throw error;
6034
6215
  }
6216
+ return asn1SchemaValue;
6035
6217
  }
6036
6218
  };
6037
6219
 
@@ -6213,9 +6395,19 @@ async function createSelfSignedCertificate({
6213
6395
  }
6214
6396
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6215
6397
  const alternativeNameExtensions = [];
6216
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6217
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6218
- 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
+ }
6219
6411
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6220
6412
  const s = new Subject(subject || "");
6221
6413
  const s1 = s.toStringInternal(", ");
@@ -6247,19 +6439,37 @@ async function createSelfSignedCertificate({
6247
6439
  // source/index_web.ts
6248
6440
  var asn1 = { readDirectoryName, readTag, readStruct, readAlgorithmIdentifier, readSignatureValueBin };
6249
6441
 
6250
- // source_nodejs/read.ts
6251
- var import_assert8 = __toESM(require("assert"));
6442
+ // source_nodejs/generate_private_key_filename.ts
6252
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"));
6253
6464
  var import_node_path = __toESM(require("path"));
6254
- var import_crypto13 = require("crypto");
6255
6465
  var import_sshpk = __toESM(require("sshpk"));
6256
6466
  function _readPemFile(filename) {
6257
- (0, import_assert8.default)(typeof filename === "string");
6258
- 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"));
6259
6469
  }
6260
6470
  function _readPemOrDerFileAsDER(filename) {
6261
6471
  if (filename.match(/.*\.der/)) {
6262
- return import_node_fs.default.readFileSync(filename);
6472
+ return import_node_fs2.default.readFileSync(filename);
6263
6473
  }
6264
6474
  const raw_key = _readPemFile(filename);
6265
6475
  return convertPEMtoDER(raw_key);
@@ -6269,34 +6479,35 @@ function readCertificate(filename) {
6269
6479
  }
6270
6480
  function readPublicKey(filename) {
6271
6481
  if (filename.match(/.*\.der/)) {
6272
- const der = import_node_fs.default.readFileSync(filename);
6273
- return (0, import_crypto13.createPublicKey)(der);
6482
+ const der = import_node_fs2.default.readFileSync(filename);
6483
+ return (0, import_node_crypto6.createPublicKey)(der);
6274
6484
  } else {
6275
6485
  const raw_key = _readPemFile(filename);
6276
- return (0, import_crypto13.createPublicKey)(raw_key);
6486
+ return (0, import_node_crypto6.createPublicKey)(raw_key);
6277
6487
  }
6278
6488
  }
6279
6489
  function myCreatePrivateKey(rawKey) {
6280
- if (!import_crypto13.createPrivateKey || process.env.NO_CREATE_PRIVATEKEY) {
6490
+ if (!import_node_crypto6.createPrivateKey || process.env.NO_CREATE_PRIVATEKEY) {
6281
6491
  if (Buffer.isBuffer(rawKey)) {
6282
6492
  const pemKey = toPem(rawKey, "PRIVATE KEY");
6283
- (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);
6284
6494
  return { hidden: pemKey };
6285
6495
  }
6286
6496
  return { hidden: ensureTrailingLF(rawKey) };
6287
6497
  }
6288
6498
  const backup = process.env.OPENSSL_CONF;
6289
6499
  process.env.OPENSSL_CONF = "/dev/null";
6290
- const retValue = (0, import_crypto13.createPrivateKey)(rawKey);
6500
+ const retValue = (0, import_node_crypto6.createPrivateKey)(rawKey);
6291
6501
  process.env.OPENSSL_CONF = backup;
6292
6502
  return { hidden: retValue };
6293
6503
  }
6294
6504
  function ensureTrailingLF(str) {
6295
- return str.match(/\n$/) ? str : str + "\n";
6505
+ return str.match(/\n$/) ? str : `${str}
6506
+ `;
6296
6507
  }
6297
6508
  function readPrivateKey(filename) {
6298
6509
  if (filename.match(/.*\.der/)) {
6299
- const der = import_node_fs.default.readFileSync(filename);
6510
+ const der = import_node_fs2.default.readFileSync(filename);
6300
6511
  return myCreatePrivateKey(der);
6301
6512
  } else {
6302
6513
  const raw_key = _readPemFile(filename);
@@ -6325,32 +6536,32 @@ function getCertificateStore() {
6325
6536
  return _g_certificate_store;
6326
6537
  }
6327
6538
  function readPrivateRsaKey(filename) {
6328
- if (!import_crypto13.createPrivateKey) {
6539
+ if (!import_node_crypto6.createPrivateKey) {
6329
6540
  throw new Error("createPrivateKey is not supported in this environment");
6330
6541
  }
6331
- if (filename.substring(0, 1) !== "." && !import_node_fs.default.existsSync(filename)) {
6542
+ if (filename.substring(0, 1) !== "." && !import_node_fs2.default.existsSync(filename)) {
6332
6543
  filename = import_node_path.default.join(getCertificateStore(), filename);
6333
6544
  }
6334
- const content = import_node_fs.default.readFileSync(filename, "utf8");
6545
+ const content = import_node_fs2.default.readFileSync(filename, "utf8");
6335
6546
  const sshKey = import_sshpk.default.parsePrivateKey(content, "auto");
6336
6547
  const key = sshKey.toString("pkcs1");
6337
- const hidden = (0, import_crypto13.createPrivateKey)({ format: "pem", type: "pkcs1", key });
6548
+ const hidden = (0, import_node_crypto6.createPrivateKey)({ format: "pem", type: "pkcs1", key });
6338
6549
  return { hidden };
6339
6550
  }
6340
6551
  function readPublicRsaKey(filename) {
6341
- if (filename.substring(0, 1) !== "." && !import_node_fs.default.existsSync(filename)) {
6552
+ if (filename.substring(0, 1) !== "." && !import_node_fs2.default.existsSync(filename)) {
6342
6553
  filename = import_node_path.default.join(getCertificateStore(), filename);
6343
6554
  }
6344
- const content = import_node_fs.default.readFileSync(filename, "utf-8");
6555
+ const content = import_node_fs2.default.readFileSync(filename, "utf-8");
6345
6556
  const sshKey = import_sshpk.default.parseKey(content, "ssh");
6346
6557
  const key = sshKey.toString("pkcs1");
6347
- return (0, import_crypto13.createPublicKey)({ format: "pem", type: "pkcs1", key });
6558
+ return (0, import_node_crypto6.createPublicKey)({ format: "pem", type: "pkcs1", key });
6348
6559
  }
6349
6560
 
6350
6561
  // source_nodejs/read_certificate_revocation_list.ts
6351
- var import_node_fs2 = __toESM(require("fs"));
6562
+ var import_node_fs3 = __toESM(require("fs"));
6352
6563
  async function readCertificateRevocationList(filename) {
6353
- const crl = await import_node_fs2.default.promises.readFile(filename);
6564
+ const crl = await import_node_fs3.default.promises.readFile(filename);
6354
6565
  if (crl[0] === 48 && crl[1] === 130) {
6355
6566
  return crl;
6356
6567
  }
@@ -6359,33 +6570,15 @@ async function readCertificateRevocationList(filename) {
6359
6570
  }
6360
6571
 
6361
6572
  // source_nodejs/read_certificate_signing_request.ts
6362
- var import_node_fs3 = __toESM(require("fs"));
6573
+ var import_node_fs4 = __toESM(require("fs"));
6363
6574
  async function readCertificateSigningRequest(filename) {
6364
- const csr = await import_node_fs3.default.promises.readFile(filename);
6575
+ const csr = await import_node_fs4.default.promises.readFile(filename);
6365
6576
  if (csr[0] === 48 && csr[1] === 130) {
6366
6577
  return csr;
6367
6578
  }
6368
6579
  const raw_crl = csr.toString();
6369
6580
  return convertPEMtoDER(raw_crl);
6370
6581
  }
6371
-
6372
- // source_nodejs/generate_private_key_filename.ts
6373
- var import_node_fs4 = __toESM(require("fs"));
6374
- var import_jsrsasign3 = __toESM(require("jsrsasign"));
6375
- async function generatePrivateKeyFile(privateKeyFilename, modulusLength) {
6376
- const keys = await generateKeyPair(modulusLength);
6377
- const privateKeyPem = await privateKeyToPEM(keys.privateKey);
6378
- await import_node_fs4.default.promises.writeFile(privateKeyFilename, privateKeyPem.privPem, "utf-8");
6379
- privateKeyPem.privPem = "";
6380
- privateKeyPem.privDer = new ArrayBuffer(0);
6381
- }
6382
- async function generatePrivateKeyFileAlternate(privateKeyFilename, modulusLength) {
6383
- const kp = import_jsrsasign3.default.KEYUTIL.generateKeypair("RSA", modulusLength);
6384
- const prv = kp.prvKeyObj;
6385
- const pub = kp.pubKeyObj;
6386
- const prvpem = import_jsrsasign3.default.KEYUTIL.getPEM(prv, "PKCS8PRV");
6387
- await import_node_fs4.default.promises.writeFile(privateKeyFilename, prvpem, "utf-8");
6388
- }
6389
6582
  // Annotate the CommonJS export names for ESM import in node:
6390
6583
  0 && (module.exports = {
6391
6584
  CertificatePurpose,
@@ -6481,7 +6674,7 @@ pvtsutils/build/index.es.js:
6481
6674
  (*!
6482
6675
  * MIT License
6483
6676
  *
6484
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
6677
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
6485
6678
  *
6486
6679
  * Permission is hereby granted, free of charge, to any person obtaining a copy
6487
6680
  * of this software and associated documentation files (the "Software"), to deal