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.
@@ -105,8 +105,29 @@ __export(index_web_exports, {
105
105
  });
106
106
  module.exports = __toCommonJS(index_web_exports);
107
107
 
108
+ // source/common.ts
109
+ var import_node_crypto = __toESM(require("crypto"));
110
+ var KeyObjectOrig = import_node_crypto.default.KeyObject;
111
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_node_crypto.default;
112
+ function isKeyObject(mayBeKeyObject) {
113
+ if (KeyObjectOrig) {
114
+ return mayBeKeyObject instanceof KeyObjectOrig;
115
+ }
116
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
117
+ }
118
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
119
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
120
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
121
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
122
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
123
+ return CertificatePurpose2;
124
+ })(CertificatePurpose || {});
125
+
126
+ // source/crypto_explore_certificate.ts
127
+ var import_node_assert4 = __toESM(require("assert"));
128
+
108
129
  // source/asn1.ts
109
- var import_assert = __toESM(require("assert"));
130
+ var import_node_assert = __toESM(require("assert"));
110
131
 
111
132
  // source/oid_map.ts
112
133
  var oid_map = {
@@ -442,7 +463,7 @@ var TagType = /* @__PURE__ */ ((TagType2) => {
442
463
  function readTag(buf, pos) {
443
464
  const start = pos;
444
465
  if (buf.length <= pos) {
445
- throw new Error("Invalid position : buf.length=" + buf.length + " pos =" + pos);
466
+ throw new Error(`Invalid position : buf.length=${buf.length} pos=${pos}`);
446
467
  }
447
468
  const tag = buf.readUInt8(pos);
448
469
  pos += 1;
@@ -471,7 +492,8 @@ function readStruct(buf, blockInfo) {
471
492
  return blocks;
472
493
  }
473
494
  function parseBitString(buffer, start, end, maxLength) {
474
- const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = "(" + lenBit + " bit)\n";
495
+ const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = `(${lenBit} bit)
496
+ `;
475
497
  let s = "", skip = unusedBit;
476
498
  for (let i = end - 1; i > start; --i) {
477
499
  const b = buffer.readUInt8(i);
@@ -479,12 +501,12 @@ function parseBitString(buffer, start, end, maxLength) {
479
501
  s += b >> j & 1 ? "1" : "0";
480
502
  }
481
503
  skip = 0;
482
- (0, import_assert.default)(s.length <= maxLength);
504
+ (0, import_node_assert.default)(s.length <= maxLength);
483
505
  }
484
506
  return intro + s;
485
507
  }
486
508
  function readBitString(buffer, block) {
487
- (0, import_assert.default)(block.tag === 3 /* BIT_STRING */);
509
+ (0, import_node_assert.default)(block.tag === 3 /* BIT_STRING */);
488
510
  const data = getBlock(buffer, block);
489
511
  const ignore_bits = data.readUInt8(0);
490
512
  return {
@@ -497,14 +519,14 @@ function readBitString(buffer, block) {
497
519
  function formatBuffer2DigitHexWithColum(buffer) {
498
520
  const value = [];
499
521
  for (let i = 0; i < buffer.length; i++) {
500
- value.push(("00" + buffer.readUInt8(i).toString(16)).substr(-2, 2));
522
+ value.push(`00${buffer.readUInt8(i).toString(16)}`.substr(-2, 2));
501
523
  }
502
524
  return value.join(":").toUpperCase().replace(/^(00:)*/, "");
503
525
  }
504
526
  function readOctetString(buffer, block) {
505
- (0, import_assert.default)(block.tag === 4 /* OCTET_STRING */);
527
+ (0, import_node_assert.default)(block.tag === 4 /* OCTET_STRING */);
506
528
  const tag = readTag(buffer, block.position);
507
- (0, import_assert.default)(tag.tag === 4 /* OCTET_STRING */);
529
+ (0, import_node_assert.default)(tag.tag === 4 /* OCTET_STRING */);
508
530
  const nbBytes = tag.length;
509
531
  const pos = tag.position;
510
532
  const b = buffer.subarray(pos, pos + nbBytes);
@@ -534,19 +556,19 @@ function parseOID(buffer, start, end) {
534
556
  if (!(v & 128)) {
535
557
  if (s === "") {
536
558
  const m = n < 80 ? n < 40 ? 0 : 1 : 2;
537
- s = m + "." + (n - m * 40);
559
+ s = `${m}.${n - m * 40}`;
538
560
  } else {
539
- s += "." + n.toString();
561
+ s += `.${n.toString()}`;
540
562
  }
541
563
  n = 0;
542
564
  bits = 0;
543
565
  }
544
566
  }
545
- (0, import_assert.default)(bits === 0);
567
+ (0, import_node_assert.default)(bits === 0);
546
568
  return s;
547
569
  }
548
570
  function readObjectIdentifier(buffer, block) {
549
- (0, import_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
571
+ (0, import_node_assert.default)(block.tag === 6 /* OBJECT_IDENTIFIER */);
550
572
  const b = buffer.subarray(block.position, block.position + block.length);
551
573
  const oid = parseOID(b, 0, block.length);
552
574
  return {
@@ -574,17 +596,17 @@ function readSignatureValue(buffer, block) {
574
596
  return readSignatureValueBin(buffer, block).toString("hex");
575
597
  }
576
598
  function readLongIntegerValue(buffer, block) {
577
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
599
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
578
600
  const pos = block.position;
579
601
  const nbBytes = block.length;
580
602
  const buf = buffer.subarray(pos, pos + nbBytes);
581
603
  return buf;
582
604
  }
583
605
  function readIntegerValue(buffer, block) {
584
- (0, import_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
606
+ (0, import_node_assert.default)(block.tag === 2 /* INTEGER */, "expecting a INTEGER tag");
585
607
  let pos = block.position;
586
608
  const nbBytes = block.length;
587
- (0, import_assert.default)(nbBytes < 4);
609
+ (0, import_node_assert.default)(nbBytes < 4);
588
610
  let value = 0;
589
611
  for (let i = 0; i < nbBytes; i++) {
590
612
  value = value * 256 + buffer.readUInt8(pos);
@@ -593,11 +615,11 @@ function readIntegerValue(buffer, block) {
593
615
  return value;
594
616
  }
595
617
  function readBooleanValue(buffer, block) {
596
- (0, import_assert.default)(block.tag === 1 /* BOOLEAN */, "expecting a BOOLEAN tag. got " + TagType[block.tag]);
618
+ (0, import_node_assert.default)(block.tag === 1 /* BOOLEAN */, `expecting a BOOLEAN tag. got ${TagType[block.tag]}`);
597
619
  const pos = block.position;
598
620
  const nbBytes = block.length;
599
- (0, import_assert.default)(nbBytes < 4);
600
- const value = buffer.readUInt8(pos) ? true : false;
621
+ (0, import_node_assert.default)(nbBytes < 4);
622
+ const value = !!buffer.readUInt8(pos);
601
623
  return value;
602
624
  }
603
625
  function readVersionValue(buffer, block) {
@@ -649,7 +671,7 @@ function readValue(buffer, block) {
649
671
  case 24 /* GeneralizedTime */:
650
672
  return convertGeneralizedTime(getBlock(buffer, block).toString("ascii"));
651
673
  default:
652
- throw new Error("Invalid tag 0x" + block.tag.toString(16));
674
+ throw new Error(`Invalid tag 0x${block.tag.toString(16)}`);
653
675
  }
654
676
  }
655
677
  function findBlockAtIndex(blocks, index) {
@@ -664,31 +686,229 @@ function readTime(buffer, block) {
664
686
  }
665
687
 
666
688
  // source/crypto_utils.ts
667
- var import_constants = __toESM(require("constants"));
668
- var import_assert4 = __toESM(require("assert"));
669
- var import_crypto = require("crypto");
670
- var import_hexy = __toESM(require("hexy"));
689
+ var import_node_assert2 = __toESM(require("assert"));
690
+ var import_node_constants = __toESM(require("constants"));
691
+ var import_node_crypto2 = require("crypto");
692
+ var import_jsrsasign = __toESM(require("jsrsasign"));
671
693
 
672
694
  // source/buffer_utils.ts
673
695
  var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (size) => {
674
696
  return new Buffer(size);
675
697
  };
676
698
 
677
- // source/crypto_explore_certificate.ts
678
- var import_assert3 = __toESM(require("assert"));
699
+ // source/hexy.ts
700
+ function hexy(buffer, { width, format } = {}) {
701
+ width = width || 80;
702
+ if (format === "twos") {
703
+ width = 26 * 3;
704
+ }
705
+ const regex = new RegExp(`.{1,${width}}`, "g");
706
+ const regexTwos = new RegExp(`.{1,${2}}`, "g");
707
+ let fullHex = buffer.toString("hex");
708
+ if (format === "twos") {
709
+ fullHex = fullHex.match(regexTwos)?.join(" ") || "";
710
+ }
711
+ return fullHex.match(regex)?.join("\n") || "";
712
+ }
713
+
714
+ // source/crypto_utils.ts
715
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
716
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
717
+ function identifyPemType(rawKey) {
718
+ if (Buffer.isBuffer(rawKey)) {
719
+ rawKey = rawKey.toString("utf8");
720
+ }
721
+ const match = PEM_TYPE_REGEX.exec(rawKey);
722
+ return !match ? void 0 : match[2];
723
+ }
724
+ function removeTrailingLF(str) {
725
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
726
+ return tmp;
727
+ }
728
+ function toPem(raw_key, pem) {
729
+ (0, import_node_assert2.default)(raw_key, "expecting a key");
730
+ (0, import_node_assert2.default)(typeof pem === "string");
731
+ let pemType = identifyPemType(raw_key);
732
+ if (pemType) {
733
+ return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
734
+ } else {
735
+ pemType = pem;
736
+ (0, import_node_assert2.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
737
+ let b = raw_key.toString("base64");
738
+ let str = `-----BEGIN ${pemType}-----
739
+ `;
740
+ while (b.length) {
741
+ str += `${b.substring(0, 64)}
742
+ `;
743
+ b = b.substring(64);
744
+ }
745
+ str += `-----END ${pemType}-----`;
746
+ return str;
747
+ }
748
+ }
749
+ function convertPEMtoDER(raw_key) {
750
+ let match;
751
+ let _pemType;
752
+ let base64str;
753
+ const parts = [];
754
+ PEM_REGEX.lastIndex = 0;
755
+ match = PEM_REGEX.exec(raw_key);
756
+ while (match !== null) {
757
+ _pemType = match[2];
758
+ base64str = match[3];
759
+ base64str = base64str.replace(/\r?\n/g, "");
760
+ parts.push(Buffer.from(base64str, "base64"));
761
+ match = PEM_REGEX.exec(raw_key);
762
+ }
763
+ return combine_der(parts);
764
+ }
765
+ function hexDump(buffer, width) {
766
+ if (!buffer) {
767
+ return "<>";
768
+ }
769
+ width = width || 32;
770
+ if (buffer.length > 1024) {
771
+ return `${hexy(buffer.subarray(0, 1024), { width, format: "twos" })}
772
+ .... ( ${buffer.length})`;
773
+ } else {
774
+ return hexy(buffer, { width, format: "twos" });
775
+ }
776
+ }
777
+ function makeMessageChunkSignature(chunk, options) {
778
+ const signer = (0, import_node_crypto2.createSign)(options.algorithm);
779
+ signer.update(chunk);
780
+ const signature = signer.sign(options.privateKey.hidden);
781
+ (0, import_node_assert2.default)(!options.signatureLength || signature.length === options.signatureLength);
782
+ return signature;
783
+ }
784
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
785
+ const verify = (0, import_node_crypto2.createVerify)(options.algorithm);
786
+ verify.update(blockToVerify);
787
+ return verify.verify(options.publicKey, signature);
788
+ }
789
+ function makeSHA1Thumbprint(buffer) {
790
+ return (0, import_node_crypto2.createHash)("sha1").update(buffer).digest();
791
+ }
792
+ var RSA_PKCS1_OAEP_PADDING = import_node_constants.default.RSA_PKCS1_OAEP_PADDING;
793
+ var RSA_PKCS1_PADDING = import_node_constants.default.RSA_PKCS1_PADDING;
794
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
795
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
796
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
797
+ return PaddingAlgorithm2;
798
+ })(PaddingAlgorithm || {});
799
+ (0, import_node_assert2.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_node_constants.default.RSA_PKCS1_OAEP_PADDING);
800
+ (0, import_node_assert2.default)(1 /* RSA_PKCS1_PADDING */ === import_node_constants.default.RSA_PKCS1_PADDING);
801
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
802
+ if (algorithm === void 0) {
803
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
804
+ }
805
+ return (0, import_node_crypto2.publicEncrypt)(
806
+ {
807
+ key: publicKey,
808
+ padding: algorithm
809
+ },
810
+ buffer
811
+ );
812
+ }
813
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
814
+ if (algorithm === void 0) {
815
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
816
+ }
817
+ try {
818
+ return (0, import_node_crypto2.privateDecrypt)(
819
+ {
820
+ key: privateKey.hidden,
821
+ padding: algorithm
822
+ },
823
+ buffer
824
+ );
825
+ } catch (_err) {
826
+ return Buffer.alloc(1);
827
+ }
828
+ }
829
+ var publicEncrypt = publicEncrypt_native;
830
+ var privateDecrypt = privateDecrypt_native;
831
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
832
+ if (paddingAlgorithm === void 0) {
833
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
834
+ }
835
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
836
+ padding = padding || 11;
837
+ if (padding !== 11) throw new Error("padding should be 11");
838
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
839
+ padding = padding || 42;
840
+ if (padding !== 42) throw new Error("padding should be 42");
841
+ } else {
842
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
843
+ }
844
+ const chunk_size = blockSize - padding;
845
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
846
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
847
+ for (let i = 0; i < nbBlocks; i++) {
848
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
849
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
850
+ if (encrypted_chunk.length !== blockSize) {
851
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
852
+ }
853
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
854
+ }
855
+ return outputBuffer;
856
+ }
857
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
858
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
859
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
860
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
861
+ }
862
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
863
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
864
+ let total_length = 0;
865
+ for (let i = 0; i < nbBlocks; i++) {
866
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
867
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
868
+ decrypted_buf.copy(outputBuffer, total_length);
869
+ total_length += decrypted_buf.length;
870
+ }
871
+ return outputBuffer.subarray(0, total_length);
872
+ }
873
+ function coerceCertificatePem(certificate) {
874
+ if (Buffer.isBuffer(certificate)) {
875
+ certificate = toPem(certificate, "CERTIFICATE");
876
+ }
877
+ (0, import_node_assert2.default)(typeof certificate === "string");
878
+ return certificate;
879
+ }
880
+ function extractPublicKeyFromCertificateSync(certificate) {
881
+ certificate = coerceCertificatePem(certificate);
882
+ const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
883
+ const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
884
+ (0, import_node_assert2.default)(typeof publicKeyAsPem === "string");
885
+ return publicKeyAsPem;
886
+ }
887
+ function extractPublicKeyFromCertificate(certificate, callback) {
888
+ let err1 = null;
889
+ let keyPem;
890
+ try {
891
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
892
+ } catch (err) {
893
+ err1 = err;
894
+ }
895
+ setImmediate(() => {
896
+ callback(err1, keyPem);
897
+ });
898
+ }
679
899
 
680
900
  // source/directory_name.ts
681
- var import_assert2 = __toESM(require("assert"));
901
+ var import_node_assert3 = __toESM(require("assert"));
682
902
  function readDirectoryName(buffer, block) {
683
903
  const set_blocks = readStruct(buffer, block);
684
904
  const names = {};
685
905
  for (const set_block of set_blocks) {
686
- (0, import_assert2.default)(set_block.tag === 49);
906
+ (0, import_node_assert3.default)(set_block.tag === 49);
687
907
  const blocks = readStruct(buffer, set_block);
688
- (0, import_assert2.default)(blocks.length === 1);
689
- (0, import_assert2.default)(blocks[0].tag === 48);
908
+ (0, import_node_assert3.default)(blocks.length === 1);
909
+ (0, import_node_assert3.default)(blocks[0].tag === 48);
690
910
  const sequenceBlock = readStruct(buffer, blocks[0]);
691
- (0, import_assert2.default)(sequenceBlock.length === 2);
911
+ (0, import_node_assert3.default)(sequenceBlock.length === 2);
692
912
  const type = readObjectIdentifier(buffer, sequenceBlock[0]);
693
913
  names[type.name] = readValue(buffer, sequenceBlock[1]);
694
914
  }
@@ -768,7 +988,7 @@ function _readAuthorityKeyIdentifier(buffer) {
768
988
  // can be null for self-signed certf
769
989
  };
770
990
  }
771
- function readBasicConstraint2_5_29_19(buffer, block) {
991
+ function readBasicConstraint2_5_29_19(buffer, _block) {
772
992
  const block_info = readTag(buffer, 0);
773
993
  const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
774
994
  let cA = false;
@@ -813,14 +1033,14 @@ function _readGeneralNames(buffer, block) {
813
1033
  }
814
1034
  const n = {};
815
1035
  for (const block2 of blocks) {
816
- (0, import_assert3.default)((block2.tag & 128) === 128);
1036
+ (0, import_node_assert4.default)((block2.tag & 128) === 128);
817
1037
  const t2 = block2.tag & 127;
818
1038
  const type = _data[t2];
819
1039
  if (!type) {
820
- console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
1040
+ console.log(`_readGeneralNames: INVALID TYPE => ${t2} 0x${t2.toString(16)}`);
821
1041
  continue;
822
1042
  }
823
- if (t2 == 32) {
1043
+ if (t2 === 32) {
824
1044
  n[type.name] = n[type.name] || [];
825
1045
  const blocks2 = readStruct(buffer, block2);
826
1046
  const name = readObjectIdentifier(buffer, blocks2[0]).name;
@@ -843,7 +1063,7 @@ function _readSubjectAltNames(buffer) {
843
1063
  const block_info = readTag(buffer, 0);
844
1064
  return _readGeneralNames(buffer, block_info);
845
1065
  }
846
- function readKeyUsage(oid, buffer) {
1066
+ function readKeyUsage(_oid, buffer) {
847
1067
  const block_info = readTag(buffer, 0);
848
1068
  let b2 = 0;
849
1069
  let b3 = 0;
@@ -873,7 +1093,7 @@ function readKeyUsage(oid, buffer) {
873
1093
  };
874
1094
  }
875
1095
  function readExtKeyUsage(oid, buffer) {
876
- (0, import_assert3.default)(oid === "2.5.29.37");
1096
+ (0, import_node_assert4.default)(oid === "2.5.29.37");
877
1097
  const block_info = readTag(buffer, 0);
878
1098
  const inner_blocks = readStruct(buffer, block_info);
879
1099
  const extKeyUsage = {
@@ -903,7 +1123,7 @@ function _readSubjectPublicKey(buffer) {
903
1123
  function readExtension(buffer, block) {
904
1124
  const inner_blocks = readStruct(buffer, block);
905
1125
  if (inner_blocks.length === 3) {
906
- (0, import_assert3.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
1126
+ (0, import_node_assert4.default)(inner_blocks[1].tag === 1 /* BOOLEAN */);
907
1127
  inner_blocks[1] = inner_blocks[2];
908
1128
  }
909
1129
  const identifier = readObjectIdentifier(buffer, inner_blocks[0]);
@@ -923,7 +1143,7 @@ function readExtension(buffer, block) {
923
1143
  value = readBasicConstraint2_5_29_19(buf, inner_blocks[1]);
924
1144
  break;
925
1145
  case "certExtension":
926
- value = "basicConstraints ( not implemented yet) " + buf.toString("hex");
1146
+ value = `basicConstraints ( not implemented yet) ${buf.toString("hex")}`;
927
1147
  break;
928
1148
  case "extKeyUsage":
929
1149
  value = readExtKeyUsage(identifier.oid, buf);
@@ -932,7 +1152,7 @@ function readExtension(buffer, block) {
932
1152
  value = readKeyUsage(identifier.oid, buf);
933
1153
  break;
934
1154
  default:
935
- value = "Unknown " + identifier.name + buf.toString("hex");
1155
+ value = `Unknown ${identifier.name}${buf.toString("hex")}`;
936
1156
  }
937
1157
  return {
938
1158
  identifier,
@@ -940,7 +1160,7 @@ function readExtension(buffer, block) {
940
1160
  };
941
1161
  }
942
1162
  function _readExtensions(buffer, block) {
943
- (0, import_assert3.default)(block.tag === 163);
1163
+ (0, import_node_assert4.default)(block.tag === 163);
944
1164
  let inner_blocks = readStruct(buffer, block);
945
1165
  inner_blocks = readStruct(buffer, inner_blocks[0]);
946
1166
  const extensions = inner_blocks.map((block2) => readExtension(buffer, block2));
@@ -979,10 +1199,17 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
979
1199
  }
980
1200
  function readTbsCertificate(buffer, block) {
981
1201
  const blocks = readStruct(buffer, block);
982
- let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1202
+ let _version;
1203
+ let serialNumber;
1204
+ let signature;
1205
+ let issuer;
1206
+ let validity;
1207
+ let subject;
1208
+ let subjectFingerPrint;
1209
+ let extensions;
983
1210
  let subjectPublicKeyInfo;
984
1211
  if (blocks.length === 6) {
985
- version = 1;
1212
+ _version = 1;
986
1213
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[0]));
987
1214
  signature = readAlgorithmIdentifier(buffer, blocks[1]);
988
1215
  issuer = _readName(buffer, blocks[2]);
@@ -996,7 +1223,7 @@ function readTbsCertificate(buffer, block) {
996
1223
  if (!version_block) {
997
1224
  throw new Error("cannot find version block");
998
1225
  }
999
- version = readVersionValue(buffer, version_block) + 1;
1226
+ _version = readVersionValue(buffer, version_block) + 1;
1000
1227
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[1]));
1001
1228
  signature = readAlgorithmIdentifier(buffer, blocks[2]);
1002
1229
  issuer = _readName(buffer, blocks[3]);
@@ -1010,22 +1237,22 @@ function readTbsCertificate(buffer, block) {
1010
1237
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
1011
1238
  break;
1012
1239
  }
1013
- case "ecPublicKey":
1014
1240
  default: {
1241
+ (0, import_node_assert4.default)(what_type === "ecPublicKey");
1015
1242
  subjectPublicKeyInfo = _readSubjectECCPublicKeyInfo(buffer, blocks[6]);
1016
1243
  break;
1017
1244
  }
1018
1245
  }
1019
1246
  const extensionBlock = findBlockAtIndex(blocks, 3);
1020
1247
  if (!extensionBlock) {
1021
- doDebug && console.log("X509 certificate is invalid : cannot find extension block version =" + version_block);
1248
+ doDebug && console.log(`X509 certificate is invalid : cannot find extension block version = ${version_block}`);
1022
1249
  extensions = null;
1023
1250
  } else {
1024
1251
  extensions = _readExtensions(buffer, extensionBlock);
1025
1252
  }
1026
1253
  }
1027
1254
  return {
1028
- version,
1255
+ version: _version,
1029
1256
  serialNumber,
1030
1257
  signature,
1031
1258
  issuer,
@@ -1037,17 +1264,18 @@ function readTbsCertificate(buffer, block) {
1037
1264
  };
1038
1265
  }
1039
1266
  function exploreCertificate(certificate) {
1040
- (0, import_assert3.default)(Buffer.isBuffer(certificate));
1041
- if (!certificate._exploreCertificate_cache) {
1267
+ (0, import_node_assert4.default)(Buffer.isBuffer(certificate));
1268
+ const certificate_priv = certificate;
1269
+ if (!certificate_priv._exploreCertificate_cache) {
1042
1270
  const block_info = readTag(certificate, 0);
1043
1271
  const blocks = readStruct(certificate, block_info);
1044
- certificate._exploreCertificate_cache = {
1272
+ certificate_priv._exploreCertificate_cache = {
1045
1273
  tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1046
1274
  signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1047
1275
  signatureValue: readSignatureValue(certificate, blocks[2])
1048
1276
  };
1049
1277
  }
1050
- return certificate._exploreCertificate_cache;
1278
+ return certificate_priv._exploreCertificate_cache;
1051
1279
  }
1052
1280
  function split_der(certificateChain) {
1053
1281
  const certificate_chain = [];
@@ -1066,383 +1294,81 @@ function combine_der(certificates) {
1066
1294
  let sum = 0;
1067
1295
  b.forEach((block) => {
1068
1296
  const block_info = readTag(block, 0);
1069
- (0, import_assert3.default)(block_info.position + block_info.length === block.length);
1297
+ (0, import_node_assert4.default)(block_info.position + block_info.length === block.length);
1070
1298
  sum += block.length;
1071
1299
  });
1072
- (0, import_assert3.default)(sum === cert.length);
1300
+ (0, import_node_assert4.default)(sum === cert.length);
1073
1301
  }
1074
1302
  return Buffer.concat(certificates);
1075
1303
  }
1076
1304
 
1077
- // source/crypto_utils.ts
1078
- var import_jsrsasign = __toESM(require("jsrsasign"));
1079
- var { hexy } = import_hexy.default;
1080
- var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
1081
- var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
1082
- function identifyPemType(rawKey) {
1083
- if (Buffer.isBuffer(rawKey)) {
1084
- rawKey = rawKey.toString("utf8");
1085
- }
1086
- const match = PEM_TYPE_REGEX.exec(rawKey);
1087
- return !match ? void 0 : match[2];
1088
- }
1089
- function removeTrailingLF(str) {
1090
- const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1091
- return tmp;
1305
+ // source/crypto_utils2.ts
1306
+ var import_node_assert5 = __toESM(require("assert"));
1307
+ var import_jsrsasign2 = __toESM(require("jsrsasign"));
1308
+ function rsaLengthPrivateKey(key) {
1309
+ const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
1310
+ const a = import_jsrsasign2.default.KEYUTIL.getKey(keyPem);
1311
+ return a.n.toString(16).length / 2;
1092
1312
  }
1093
- function toPem(raw_key, pem) {
1094
- (0, import_assert4.default)(raw_key, "expecting a key");
1095
- (0, import_assert4.default)(typeof pem === "string");
1096
- let pemType = identifyPemType(raw_key);
1097
- if (pemType) {
1098
- return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1099
- } else {
1100
- pemType = pem;
1101
- (0, import_assert4.default)(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1102
- let b = raw_key.toString("base64");
1103
- let str = "-----BEGIN " + pemType + "-----\n";
1104
- while (b.length) {
1105
- str += b.substring(0, 64) + "\n";
1106
- b = b.substring(64);
1313
+ function toPem2(raw_key, pem) {
1314
+ if (raw_key.hidden) {
1315
+ return toPem2(raw_key.hidden, pem);
1316
+ }
1317
+ (0, import_node_assert5.default)(raw_key, "expecting a key");
1318
+ (0, import_node_assert5.default)(typeof pem === "string");
1319
+ if (isKeyObject(raw_key)) {
1320
+ const _raw_key = raw_key;
1321
+ if (pem === "RSA PRIVATE KEY") {
1322
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs1" }).toString());
1323
+ } else if (pem === "PRIVATE KEY") {
1324
+ return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs8" }).toString());
1325
+ } else {
1326
+ throw new Error("Unsupported case!");
1107
1327
  }
1108
- str += "-----END " + pemType + "-----";
1109
- return str;
1110
1328
  }
1329
+ return toPem(raw_key, pem);
1111
1330
  }
1112
- function convertPEMtoDER(raw_key) {
1113
- let match;
1114
- let pemType;
1115
- let base64str;
1116
- const parts = [];
1117
- PEM_REGEX.lastIndex = 0;
1118
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1119
- pemType = match[2];
1120
- base64str = match[3];
1121
- base64str = base64str.replace(/\r?\n/g, "");
1122
- parts.push(Buffer.from(base64str, "base64"));
1123
- }
1124
- return combine_der(parts);
1331
+ function coercePrivateKeyPem(privateKey) {
1332
+ return toPem2(privateKey, "PRIVATE KEY");
1125
1333
  }
1126
- function hexDump(buffer, width) {
1127
- if (!buffer) {
1128
- return "<>";
1129
- }
1130
- width = width || 32;
1131
- if (buffer.length > 1024) {
1132
- return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1133
- } else {
1134
- return hexy(buffer, { width, format: "twos" });
1334
+ function coercePublicKeyPem(publicKey) {
1335
+ if (isKeyObject(publicKey)) {
1336
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1135
1337
  }
1338
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1339
+ return publicKey;
1136
1340
  }
1137
- function makeMessageChunkSignature(chunk, options) {
1138
- const signer = (0, import_crypto.createSign)(options.algorithm);
1139
- signer.update(chunk);
1140
- const signature = signer.sign(options.privateKey.hidden);
1141
- (0, import_assert4.default)(!options.signatureLength || signature.length === options.signatureLength);
1142
- return signature;
1143
- }
1144
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
1145
- const verify = (0, import_crypto.createVerify)(options.algorithm);
1146
- verify.update(blockToVerify);
1147
- return verify.verify(options.publicKey, signature);
1148
- }
1149
- function makeSHA1Thumbprint(buffer) {
1150
- return (0, import_crypto.createHash)("sha1").update(buffer).digest();
1151
- }
1152
- var RSA_PKCS1_OAEP_PADDING = import_constants.default.RSA_PKCS1_OAEP_PADDING;
1153
- var RSA_PKCS1_PADDING = import_constants.default.RSA_PKCS1_PADDING;
1154
- var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1155
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1156
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1157
- return PaddingAlgorithm2;
1158
- })(PaddingAlgorithm || {});
1159
- (0, import_assert4.default)(4 /* RSA_PKCS1_OAEP_PADDING */ === import_constants.default.RSA_PKCS1_OAEP_PADDING);
1160
- (0, import_assert4.default)(1 /* RSA_PKCS1_PADDING */ === import_constants.default.RSA_PKCS1_PADDING);
1161
- function publicEncrypt_native(buffer, publicKey, algorithm) {
1162
- if (algorithm === void 0) {
1163
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1164
- }
1165
- return (0, import_crypto.publicEncrypt)(
1166
- {
1167
- key: publicKey,
1168
- padding: algorithm
1169
- },
1170
- buffer
1171
- );
1172
- }
1173
- function privateDecrypt_native(buffer, privateKey, algorithm) {
1174
- if (algorithm === void 0) {
1175
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1176
- }
1177
- try {
1178
- return (0, import_crypto.privateDecrypt)(
1179
- {
1180
- key: privateKey.hidden,
1181
- padding: algorithm
1182
- },
1183
- buffer
1184
- );
1185
- } catch (err) {
1186
- return Buffer.alloc(1);
1187
- }
1188
- }
1189
- var publicEncrypt = publicEncrypt_native;
1190
- var privateDecrypt = privateDecrypt_native;
1191
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1192
- if (paddingAlgorithm === void 0) {
1193
- paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1194
- }
1195
- if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1196
- padding = padding || 11;
1197
- if (padding !== 11) throw new Error("padding should be 11");
1198
- } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1199
- padding = padding || 42;
1200
- if (padding !== 42) throw new Error("padding should be 42");
1201
- } else {
1202
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1203
- }
1204
- const chunk_size = blockSize - padding;
1205
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
1206
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1207
- for (let i = 0; i < nbBlocks; i++) {
1208
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1209
- const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1210
- if (encrypted_chunk.length !== blockSize) {
1211
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1212
- }
1213
- encrypted_chunk.copy(outputBuffer, i * blockSize);
1214
- }
1215
- return outputBuffer;
1216
- }
1217
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1218
- paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1219
- if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1220
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1221
- }
1222
- const nbBlocks = Math.ceil(buffer.length / blockSize);
1223
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1224
- let total_length = 0;
1225
- for (let i = 0; i < nbBlocks; i++) {
1226
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1227
- const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1228
- decrypted_buf.copy(outputBuffer, total_length);
1229
- total_length += decrypted_buf.length;
1230
- }
1231
- return outputBuffer.subarray(0, total_length);
1232
- }
1233
- function coerceCertificatePem(certificate) {
1234
- if (Buffer.isBuffer(certificate)) {
1235
- certificate = toPem(certificate, "CERTIFICATE");
1236
- }
1237
- (0, import_assert4.default)(typeof certificate === "string");
1238
- return certificate;
1239
- }
1240
- function extractPublicKeyFromCertificateSync(certificate) {
1241
- certificate = coerceCertificatePem(certificate);
1242
- const key = import_jsrsasign.default.KEYUTIL.getKey(certificate);
1243
- const publicKeyAsPem = import_jsrsasign.default.KEYUTIL.getPEM(key);
1244
- (0, import_assert4.default)(typeof publicKeyAsPem === "string");
1245
- return publicKeyAsPem;
1246
- }
1247
- function extractPublicKeyFromCertificate(certificate, callback) {
1248
- let err1 = null;
1249
- let keyPem;
1250
- try {
1251
- keyPem = extractPublicKeyFromCertificateSync(certificate);
1252
- } catch (err) {
1253
- err1 = err;
1254
- }
1255
- setImmediate(() => {
1256
- callback(err1, keyPem);
1257
- });
1258
- }
1259
-
1260
- // source/explore_private_key.ts
1261
- function f(buffer, b) {
1262
- return buffer.subarray(b.position + 1, b.position + b.length);
1263
- }
1264
- var doDebug2 = !!process.env.DEBUG;
1265
- function explorePrivateKey(privateKey2) {
1266
- const privateKey1 = privateKey2.hidden;
1267
- const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1268
- const block_info = readTag(privateKey, 0);
1269
- const blocks = readStruct(privateKey, block_info);
1270
- if (blocks.length === 9) {
1271
- const version2 = f(privateKey, blocks[0]);
1272
- const modulus2 = f(privateKey, blocks[1]);
1273
- const publicExponent2 = f(privateKey, blocks[2]);
1274
- const privateExponent2 = f(privateKey, blocks[3]);
1275
- const prime12 = f(privateKey, blocks[4]);
1276
- const prime22 = f(privateKey, blocks[5]);
1277
- const exponent12 = f(privateKey, blocks[6]);
1278
- const exponent22 = f(privateKey, blocks[7]);
1279
- return {
1280
- version: version2,
1281
- modulus: modulus2,
1282
- publicExponent: publicExponent2,
1283
- privateExponent: privateExponent2,
1284
- prime1: prime12,
1285
- prime2: prime22,
1286
- exponent1: exponent12,
1287
- exponent2: exponent22
1288
- };
1289
- }
1290
- if (doDebug2) {
1291
- console.log("-------------------- private key:");
1292
- console.log(block_info);
1293
- console.log(
1294
- blocks.map((b2) => ({
1295
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1296
- l: b2.length,
1297
- p: b2.position,
1298
- buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1299
- }))
1300
- );
1301
- }
1302
- const b = blocks[2];
1303
- const bb = privateKey.subarray(b.position, b.position + b.length);
1304
- const block_info1 = readTag(bb, 0);
1305
- const blocks1 = readStruct(bb, block_info1);
1306
- if (doDebug2) {
1307
- console.log(
1308
- blocks1.map((b2) => ({
1309
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1310
- l: b2.length,
1311
- p: b2.position,
1312
- buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1313
- }))
1314
- );
1315
- }
1316
- const version = f(bb, blocks1[0]);
1317
- const modulus = f(bb, blocks1[1]);
1318
- const publicExponent = f(bb, blocks1[2]);
1319
- const privateExponent = f(bb, blocks1[3]);
1320
- const prime1 = f(bb, blocks1[4]);
1321
- const prime2 = f(bb, blocks1[5]);
1322
- const exponent1 = f(bb, blocks1[6]);
1323
- const exponent2 = f(bb, blocks1[7]);
1324
- return {
1325
- version,
1326
- modulus,
1327
- publicExponent,
1328
- privateExponent,
1329
- prime1,
1330
- prime2,
1331
- exponent1,
1332
- exponent2
1333
- };
1334
- }
1335
-
1336
- // source/public_private_match.ts
1337
- function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1338
- const i = exploreCertificate(certificate);
1339
- const j = explorePrivateKey(privateKey);
1340
- const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1341
- const modulus2 = j.modulus;
1342
- if (modulus1.length != modulus2.length) {
1343
- return false;
1344
- }
1345
- return modulus1.toString("hex") === modulus2.toString("hex");
1346
- }
1347
- function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1348
- const initialBuffer = Buffer.from("Lorem Ipsum");
1349
- const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1350
- const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1351
- const finalString = decryptedBuffer.toString("utf-8");
1352
- return initialBuffer.toString("utf-8") === finalString;
1353
- }
1354
- function certificateMatchesPrivateKey(certificate, privateKey) {
1355
- const e = explorePrivateKey(privateKey);
1356
- const blockSize = e.modulus.length;
1357
- const certificatePEM = toPem(certificate, "CERTIFICATE");
1358
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1359
- }
1360
-
1361
- // source/common.ts
1362
- var import_crypto2 = __toESM(require("crypto"));
1363
- var KeyObjectOrig = import_crypto2.default.KeyObject;
1364
- var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = import_crypto2.default;
1365
- function isKeyObject(mayBeKeyObject) {
1366
- if (KeyObjectOrig) {
1367
- return mayBeKeyObject instanceof KeyObjectOrig;
1368
- }
1369
- return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1370
- }
1371
- var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1372
- CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1373
- CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1374
- CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1375
- CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1376
- return CertificatePurpose2;
1377
- })(CertificatePurpose || {});
1378
-
1379
- // source/crypto_utils2.ts
1380
- var import_assert5 = __toESM(require("assert"));
1381
- var import_jsrsasign2 = __toESM(require("jsrsasign"));
1382
- function rsaLengthPrivateKey(key) {
1383
- const keyPem = typeof key.hidden === "string" ? key.hidden : key.hidden.export({ type: "pkcs1", format: "pem" }).toString();
1384
- const a = import_jsrsasign2.default.KEYUTIL.getKey(keyPem);
1385
- return a.n.toString(16).length / 2;
1386
- }
1387
- function toPem2(raw_key, pem) {
1388
- if (raw_key.hidden) {
1389
- return toPem2(raw_key.hidden, pem);
1390
- }
1391
- (0, import_assert5.default)(raw_key, "expecting a key");
1392
- (0, import_assert5.default)(typeof pem === "string");
1393
- if (isKeyObject(raw_key)) {
1394
- const _raw_key = raw_key;
1395
- if (pem === "RSA PRIVATE KEY") {
1396
- return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs1" }).toString());
1397
- } else if (pem === "PRIVATE KEY") {
1398
- return removeTrailingLF(_raw_key.export({ format: "pem", type: "pkcs8" }).toString());
1399
- } else {
1400
- throw new Error("Unsupported case!");
1401
- }
1402
- }
1403
- return toPem(raw_key, pem);
1404
- }
1405
- function coercePrivateKeyPem(privateKey) {
1406
- return toPem2(privateKey, "PRIVATE KEY");
1407
- }
1408
- function coercePublicKeyPem(publicKey) {
1409
- if (isKeyObject(publicKey)) {
1410
- return publicKey.export({ format: "pem", type: "spki" }).toString();
1411
- }
1412
- (0, import_assert5.default)(typeof publicKey === "string");
1413
- return publicKey;
1414
- }
1415
- function coerceRsaPublicKeyPem(publicKey) {
1416
- if (isKeyObject(publicKey)) {
1417
- return publicKey.export({ format: "pem", type: "spki" }).toString();
1418
- }
1419
- (0, import_assert5.default)(typeof publicKey === "string");
1420
- return publicKey;
1341
+ function coerceRsaPublicKeyPem(publicKey) {
1342
+ if (isKeyObject(publicKey)) {
1343
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
1344
+ }
1345
+ (0, import_node_assert5.default)(typeof publicKey === "string");
1346
+ return publicKey;
1421
1347
  }
1422
1348
  function rsaLengthPublicKey(key) {
1423
1349
  key = coercePublicKeyPem(key);
1424
- (0, import_assert5.default)(typeof key === "string");
1350
+ (0, import_node_assert5.default)(typeof key === "string");
1425
1351
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1426
1352
  return a.n.toString(16).length / 2;
1427
1353
  }
1428
1354
  function rsaLengthRsaPublicKey(key) {
1429
1355
  key = coerceRsaPublicKeyPem(key);
1430
- (0, import_assert5.default)(typeof key === "string");
1356
+ (0, import_node_assert5.default)(typeof key === "string");
1431
1357
  const a = import_jsrsasign2.default.KEYUTIL.getKey(key);
1432
1358
  return a.n.toString(16).length / 2;
1433
1359
  }
1434
1360
 
1435
1361
  // source/derived_keys.ts
1436
- var import_assert7 = __toESM(require("assert"));
1437
- var import_crypto3 = require("crypto");
1362
+ var import_node_assert7 = __toESM(require("assert"));
1363
+ var import_node_crypto3 = require("crypto");
1438
1364
 
1439
1365
  // source/explore_certificate.ts
1440
- var import_assert6 = __toESM(require("assert"));
1366
+ var import_node_assert6 = __toESM(require("assert"));
1441
1367
  function coerceCertificate(certificate) {
1442
1368
  if (typeof certificate === "string") {
1443
1369
  certificate = convertPEMtoDER(certificate);
1444
1370
  }
1445
- (0, import_assert6.default)(Buffer.isBuffer(certificate));
1371
+ (0, import_node_assert6.default)(Buffer.isBuffer(certificate));
1446
1372
  return certificate;
1447
1373
  }
1448
1374
  function exploreCertificateInfo(certificate) {
@@ -1456,21 +1382,21 @@ function exploreCertificateInfo(certificate) {
1456
1382
  subject: certInfo.tbsCertificate.subject
1457
1383
  };
1458
1384
  if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1459
- throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1385
+ throw new Error(`Invalid public key length (expecting 128,256,384 or 512): ${data.publicKeyLength}`);
1460
1386
  }
1461
1387
  return data;
1462
1388
  }
1463
1389
 
1464
1390
  // source/derived_keys.ts
1465
1391
  function HMAC_HASH(sha1or256, secret, message) {
1466
- return (0, import_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1392
+ return (0, import_node_crypto3.createHmac)(sha1or256, secret).update(message).digest();
1467
1393
  }
1468
1394
  function plus(buf1, buf2) {
1469
1395
  return Buffer.concat([buf1, buf2]);
1470
1396
  }
1471
1397
  function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1472
- (0, import_assert7.default)(Buffer.isBuffer(seed));
1473
- (0, import_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1398
+ (0, import_node_assert7.default)(Buffer.isBuffer(seed));
1399
+ (0, import_node_assert7.default)(sha1or256 === "SHA1" || sha1or256 === "SHA256");
1474
1400
  const a = [];
1475
1401
  a[0] = seed;
1476
1402
  let index = 1;
@@ -1483,12 +1409,12 @@ function makePseudoRandomBuffer(secret, seed, minLength, sha1or256) {
1483
1409
  return p_hash.subarray(0, minLength);
1484
1410
  }
1485
1411
  function computeDerivedKeys(secret, seed, options) {
1486
- (0, import_assert7.default)(Number.isFinite(options.signatureLength));
1487
- (0, import_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1488
- (0, import_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1489
- (0, import_assert7.default)(typeof options.algorithm === "string");
1412
+ (0, import_node_assert7.default)(Number.isFinite(options.signatureLength));
1413
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingKeyLength));
1414
+ (0, import_node_assert7.default)(Number.isFinite(options.encryptingBlockSize));
1415
+ (0, import_node_assert7.default)(typeof options.algorithm === "string");
1490
1416
  options.sha1or256 = options.sha1or256 || "SHA1";
1491
- (0, import_assert7.default)(typeof options.sha1or256 === "string");
1417
+ (0, import_node_assert7.default)(typeof options.sha1or256 === "string");
1492
1418
  const offset1 = options.signingKeyLength;
1493
1419
  const offset2 = offset1 + options.encryptingKeyLength;
1494
1420
  const minLength = offset2 + options.encryptingBlockSize;
@@ -1513,7 +1439,7 @@ function removePadding(buffer) {
1513
1439
  return reduceLength(buffer, nbPaddingBytes);
1514
1440
  }
1515
1441
  function verifyChunkSignature(chunk, options) {
1516
- (0, import_assert7.default)(Buffer.isBuffer(chunk));
1442
+ (0, import_node_assert7.default)(Buffer.isBuffer(chunk));
1517
1443
  let signatureLength = options.signatureLength || 0;
1518
1444
  if (signatureLength === 0) {
1519
1445
  const cert = exploreCertificateInfo(options.publicKey);
@@ -1524,23 +1450,23 @@ function verifyChunkSignature(chunk, options) {
1524
1450
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1525
1451
  }
1526
1452
  function computePaddingFooter(buffer, derivedKeys) {
1527
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1453
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "encryptingBlockSize"));
1528
1454
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1529
1455
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1530
1456
  padding.fill(paddingSize);
1531
1457
  return padding;
1532
1458
  }
1533
1459
  function derivedKeys_algorithm(derivedKeys) {
1534
- (0, import_assert7.default)(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1460
+ (0, import_node_assert7.default)(Object.hasOwn(derivedKeys, "algorithm"));
1535
1461
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1536
- (0, import_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1462
+ (0, import_node_assert7.default)(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1537
1463
  return algorithm;
1538
1464
  }
1539
1465
  function encryptBufferWithDerivedKeys(buffer, derivedKeys) {
1540
1466
  const algorithm = derivedKeys_algorithm(derivedKeys);
1541
1467
  const key = derivedKeys.encryptingKey;
1542
1468
  const initVector = derivedKeys.initializationVector;
1543
- const cipher = (0, import_crypto3.createCipheriv)(algorithm, key, initVector);
1469
+ const cipher = (0, import_node_crypto3.createCipheriv)(algorithm, key, initVector);
1544
1470
  cipher.setAutoPadding(false);
1545
1471
  const encrypted_chunks = [];
1546
1472
  encrypted_chunks.push(cipher.update(buffer));
@@ -1551,7 +1477,7 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1551
1477
  const algorithm = derivedKeys_algorithm(derivedKeys);
1552
1478
  const key = derivedKeys.encryptingKey;
1553
1479
  const initVector = derivedKeys.initializationVector;
1554
- const cipher = (0, import_crypto3.createDecipheriv)(algorithm, key, initVector);
1480
+ const cipher = (0, import_node_crypto3.createDecipheriv)(algorithm, key, initVector);
1555
1481
  cipher.setAutoPadding(false);
1556
1482
  const decrypted_chunks = [];
1557
1483
  decrypted_chunks.push(cipher.update(buffer));
@@ -1559,12 +1485,12 @@ function decryptBufferWithDerivedKeys(buffer, derivedKeys) {
1559
1485
  return Buffer.concat(decrypted_chunks);
1560
1486
  }
1561
1487
  function makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys) {
1562
- (0, import_assert7.default)(Buffer.isBuffer(message));
1563
- (0, import_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1564
- (0, import_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1565
- (0, import_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1566
- const signature = (0, import_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1567
- (0, import_assert7.default)(signature.length === derivedKeys.signatureLength);
1488
+ (0, import_node_assert7.default)(Buffer.isBuffer(message));
1489
+ (0, import_node_assert7.default)(Buffer.isBuffer(derivedKeys.signingKey));
1490
+ (0, import_node_assert7.default)(typeof derivedKeys.sha1or256 === "string");
1491
+ (0, import_node_assert7.default)(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
1492
+ const signature = (0, import_node_crypto3.createHmac)(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
1493
+ (0, import_node_assert7.default)(signature.length === derivedKeys.signatureLength);
1568
1494
  return signature;
1569
1495
  }
1570
1496
  function verifyChunkSignatureWithDerivedKeys(chunk, derivedKeys) {
@@ -1609,7 +1535,7 @@ function _readTbsCertList(buffer, blockInfo) {
1609
1535
  const blocks = readStruct(buffer, blockInfo);
1610
1536
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1611
1537
  if (hasOptionalVersion) {
1612
- const version = readIntegerValue(buffer, blocks[0]);
1538
+ const _version = readIntegerValue(buffer, blocks[0]);
1613
1539
  const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1614
1540
  const issuer = readNameForCrl(buffer, blocks[2]);
1615
1541
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[2])));
@@ -1628,7 +1554,7 @@ function _readTbsCertList(buffer, blockInfo) {
1628
1554
  });
1629
1555
  }
1630
1556
  }
1631
- const ext0 = findBlockAtIndex(blocks, 0);
1557
+ const _ext0 = findBlockAtIndex(blocks, 0);
1632
1558
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1633
1559
  } else {
1634
1560
  const signature = readAlgorithmIdentifier(buffer, blocks[0]);
@@ -1668,10 +1594,21 @@ function _readExtensionRequest(buffer) {
1668
1594
  const extensions = inner_blocks.map((block1) => readExtension(buffer, block1));
1669
1595
  const result = {};
1670
1596
  for (const e of extensions) {
1671
- result[e.identifier.name] = e.value;
1597
+ switch (e.identifier.name) {
1598
+ case "basicConstraints":
1599
+ result.basicConstraints = e.value;
1600
+ break;
1601
+ case "keyUsage":
1602
+ result.keyUsage = e.value;
1603
+ break;
1604
+ case "subjectAltName":
1605
+ result.subjectAltName = e.value;
1606
+ break;
1607
+ default:
1608
+ break;
1609
+ }
1672
1610
  }
1673
- const { basicConstraints, keyUsage, subjectAltName } = result;
1674
- return { basicConstraints, keyUsage, subjectAltName };
1611
+ return result;
1675
1612
  }
1676
1613
  function readCertificationRequestInfo(buffer, block) {
1677
1614
  const blocks = readStruct(buffer, block);
@@ -1699,16 +1636,117 @@ function exploreCertificateSigningRequest(crl) {
1699
1636
  return csrInfo;
1700
1637
  }
1701
1638
 
1639
+ // source/explore_private_key.ts
1640
+ function f(buffer, b) {
1641
+ return buffer.subarray(b.position + 1, b.position + b.length);
1642
+ }
1643
+ var doDebug2 = !!process.env.DEBUG;
1644
+ function explorePrivateKey(privateKey2) {
1645
+ const privateKey1 = privateKey2.hidden;
1646
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1647
+ const block_info = readTag(privateKey, 0);
1648
+ const blocks = readStruct(privateKey, block_info);
1649
+ if (blocks.length === 9) {
1650
+ const version2 = f(privateKey, blocks[0]);
1651
+ const modulus2 = f(privateKey, blocks[1]);
1652
+ const publicExponent2 = f(privateKey, blocks[2]);
1653
+ const privateExponent2 = f(privateKey, blocks[3]);
1654
+ const prime12 = f(privateKey, blocks[4]);
1655
+ const prime22 = f(privateKey, blocks[5]);
1656
+ const exponent12 = f(privateKey, blocks[6]);
1657
+ const exponent22 = f(privateKey, blocks[7]);
1658
+ return {
1659
+ version: version2,
1660
+ modulus: modulus2,
1661
+ publicExponent: publicExponent2,
1662
+ privateExponent: privateExponent2,
1663
+ prime1: prime12,
1664
+ prime2: prime22,
1665
+ exponent1: exponent12,
1666
+ exponent2: exponent22
1667
+ };
1668
+ }
1669
+ if (doDebug2) {
1670
+ console.log("-------------------- private key:");
1671
+ console.log(block_info);
1672
+ console.log(
1673
+ blocks.map((b2) => ({
1674
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1675
+ l: b2.length,
1676
+ p: b2.position,
1677
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1678
+ }))
1679
+ );
1680
+ }
1681
+ const b = blocks[2];
1682
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1683
+ const block_info1 = readTag(bb, 0);
1684
+ const blocks1 = readStruct(bb, block_info1);
1685
+ if (doDebug2) {
1686
+ console.log(
1687
+ blocks1.map((b2) => ({
1688
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1689
+ l: b2.length,
1690
+ p: b2.position,
1691
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1692
+ }))
1693
+ );
1694
+ }
1695
+ const version = f(bb, blocks1[0]);
1696
+ const modulus = f(bb, blocks1[1]);
1697
+ const publicExponent = f(bb, blocks1[2]);
1698
+ const privateExponent = f(bb, blocks1[3]);
1699
+ const prime1 = f(bb, blocks1[4]);
1700
+ const prime2 = f(bb, blocks1[5]);
1701
+ const exponent1 = f(bb, blocks1[6]);
1702
+ const exponent2 = f(bb, blocks1[7]);
1703
+ return {
1704
+ version,
1705
+ modulus,
1706
+ publicExponent,
1707
+ privateExponent,
1708
+ prime1,
1709
+ prime2,
1710
+ exponent1,
1711
+ exponent2
1712
+ };
1713
+ }
1714
+
1702
1715
  // source/make_private_key_from_pem.ts
1703
1716
  function makePrivateKeyFromPem(privateKeyInPem) {
1704
1717
  return { hidden: privateKeyInPem };
1705
1718
  }
1706
1719
 
1707
1720
  // source/make_private_key_thumbprint.ts
1708
- function makePrivateKeyThumbPrint(privateKey) {
1721
+ function makePrivateKeyThumbPrint(_privateKey) {
1709
1722
  return Buffer.alloc(0);
1710
1723
  }
1711
1724
 
1725
+ // source/public_private_match.ts
1726
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1727
+ const i = exploreCertificate(certificate);
1728
+ const j = explorePrivateKey(privateKey);
1729
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1730
+ const modulus2 = j.modulus;
1731
+ if (modulus1.length !== modulus2.length) {
1732
+ return false;
1733
+ }
1734
+ return modulus1.toString("hex") === modulus2.toString("hex");
1735
+ }
1736
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1737
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1738
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1739
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1740
+ const finalString = decryptedBuffer.toString("utf-8");
1741
+ return initialBuffer.toString("utf-8") === finalString;
1742
+ }
1743
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1744
+ const e = explorePrivateKey(privateKey);
1745
+ const blockSize = e.modulus.length;
1746
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1747
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1748
+ }
1749
+
1712
1750
  // source/subject.ts
1713
1751
  var _keys = {
1714
1752
  C: "country",
@@ -1751,11 +1789,11 @@ var Subject = class _Subject {
1751
1789
  }
1752
1790
  const s = element.split("=");
1753
1791
  if (s.length !== 2) {
1754
- throw new Error("invalid format for " + element);
1792
+ throw new Error(`invalid format for ${element}`);
1755
1793
  }
1756
1794
  const longName = _keys[s[0]];
1757
1795
  if (!longName) {
1758
- throw new Error("Invalid field found in subject name " + s[0]);
1796
+ throw new Error(`Invalid field found in subject name ${s[0]}`);
1759
1797
  }
1760
1798
  const value = s[1];
1761
1799
  options[longName] = unquote(Buffer.from(value, "ascii").toString("utf8"));
@@ -1765,25 +1803,25 @@ var Subject = class _Subject {
1765
1803
  toStringInternal(sep) {
1766
1804
  const tmp = [];
1767
1805
  if (this.country) {
1768
- tmp.push("C=" + enquoteIfNecessary(this.country));
1806
+ tmp.push(`C=${enquoteIfNecessary(this.country)}`);
1769
1807
  }
1770
1808
  if (this.state) {
1771
- tmp.push("ST=" + enquoteIfNecessary(this.state));
1809
+ tmp.push(`ST=${enquoteIfNecessary(this.state)}`);
1772
1810
  }
1773
1811
  if (this.locality) {
1774
- tmp.push("L=" + enquoteIfNecessary(this.locality));
1812
+ tmp.push(`L=${enquoteIfNecessary(this.locality)}`);
1775
1813
  }
1776
1814
  if (this.organization) {
1777
- tmp.push("O=" + enquoteIfNecessary(this.organization));
1815
+ tmp.push(`O=${enquoteIfNecessary(this.organization)}`);
1778
1816
  }
1779
1817
  if (this.organizationalUnit) {
1780
- tmp.push("OU=" + enquoteIfNecessary(this.organizationalUnit));
1818
+ tmp.push(`OU=${enquoteIfNecessary(this.organizationalUnit)}`);
1781
1819
  }
1782
1820
  if (this.commonName) {
1783
- tmp.push("CN=" + enquoteIfNecessary(this.commonName));
1821
+ tmp.push(`CN=${enquoteIfNecessary(this.commonName)}`);
1784
1822
  }
1785
1823
  if (this.domainComponent) {
1786
- tmp.push("DC=" + enquoteIfNecessary(this.domainComponent));
1824
+ tmp.push(`DC=${enquoteIfNecessary(this.domainComponent)}`);
1787
1825
  }
1788
1826
  return tmp.join(sep);
1789
1827
  }
@@ -1792,12 +1830,12 @@ var Subject = class _Subject {
1792
1830
  }
1793
1831
  toString() {
1794
1832
  const t2 = this.toStringForOPCUA();
1795
- return t2 ? "/" + t2 : t2;
1833
+ return t2 ? `/${t2}` : t2;
1796
1834
  }
1797
1835
  };
1798
1836
 
1799
1837
  // source/verify_certificate_signature.ts
1800
- var import_crypto4 = require("crypto");
1838
+ var import_node_crypto4 = require("crypto");
1801
1839
  function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1802
1840
  const block_info = readTag(certificateOrCrl, 0);
1803
1841
  const blocks = readStruct(certificateOrCrl, block_info);
@@ -1806,7 +1844,7 @@ function verifyCertificateOrClrSignature(certificateOrCrl, parentCertificate) {
1806
1844
  const signatureValue = readSignatureValueBin(certificateOrCrl, blocks[2]);
1807
1845
  const p = split_der(parentCertificate)[0];
1808
1846
  const certPem = toPem(p, "CERTIFICATE");
1809
- const verify = (0, import_crypto4.createVerify)(signatureAlgorithm.identifier);
1847
+ const verify = (0, import_node_crypto4.createVerify)(signatureAlgorithm.identifier);
1810
1848
  verify.update(bufferToBeSigned);
1811
1849
  verify.end();
1812
1850
  return verify.verify(certPem, signatureValue);
@@ -1822,8 +1860,8 @@ async function verifyCertificateChain(certificateChain) {
1822
1860
  const cert = certificateChain[index - 1];
1823
1861
  const certParent = certificateChain[index];
1824
1862
  const certParentInfo = exploreCertificate(certParent);
1825
- const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1826
- if (!keyUsage.keyCertSign) {
1863
+ const keyUsage = certParentInfo.tbsCertificate.extensions?.keyUsage;
1864
+ if (!keyUsage || !keyUsage.keyCertSign) {
1827
1865
  return {
1828
1866
  status: "BadCertificateIssuerUseNotAllowed",
1829
1867
  reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
@@ -1863,15 +1901,15 @@ async function verifyCertificateChain(certificateChain) {
1863
1901
  }
1864
1902
 
1865
1903
  // source/x509/_crypto.ts
1866
- var x509 = __toESM(require("@peculiar/x509"));
1904
+ var import_node_crypto5 = __toESM(require("crypto"));
1867
1905
  var import_webcrypto = require("@peculiar/webcrypto");
1868
- var import_crypto5 = __toESM(require("crypto"));
1906
+ var x509 = __toESM(require("@peculiar/x509"));
1869
1907
  var x5092 = __toESM(require("@peculiar/x509"));
1870
1908
  var doDebug3 = false;
1871
1909
  var _crypto;
1872
1910
  var ignoreCrypto = process.env.IGNORE_SUBTLE_FROM_CRYPTO;
1873
1911
  if (typeof window === "undefined") {
1874
- _crypto = import_crypto5.default;
1912
+ _crypto = import_node_crypto5.default;
1875
1913
  if (!_crypto?.subtle || ignoreCrypto) {
1876
1914
  _crypto = new import_webcrypto.Crypto();
1877
1915
  doDebug3 && console.warn("using @peculiar/webcrypto");
@@ -1885,7 +1923,7 @@ if (typeof window === "undefined") {
1885
1923
  x509.cryptoProvider.set(crypto);
1886
1924
  }
1887
1925
  function getCrypto() {
1888
- return _crypto || crypto || require("crypto");
1926
+ return _crypto || crypto || import_node_crypto5.default;
1889
1927
  }
1890
1928
 
1891
1929
  // source/x509/create_key_pair.ts
@@ -1911,7 +1949,7 @@ async function privateKeyToPEM(privateKey) {
1911
1949
  }
1912
1950
  async function derToPrivateKey(privDer) {
1913
1951
  const crypto3 = getCrypto();
1914
- return await crypto3.subtle.importKey(
1952
+ const importedKey = await crypto3.subtle.importKey(
1915
1953
  "pkcs8",
1916
1954
  privDer,
1917
1955
  {
@@ -1930,6 +1968,7 @@ async function derToPrivateKey(privDer) {
1930
1968
  // "deriveBits"
1931
1969
  ]
1932
1970
  );
1971
+ return importedKey;
1933
1972
  }
1934
1973
  async function pemToPrivateKey(pem) {
1935
1974
  const privDer = x5092.PemConverter.decode(pem);
@@ -1947,54 +1986,24 @@ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1947
1986
  throw new Error("not implemented");
1948
1987
  }
1949
1988
  async function _coercePrivateKey(privateKey) {
1950
- const KeyObject4 = crypto2.KeyObject;
1989
+ const KeyObject = crypto2.KeyObject;
1951
1990
  if (Buffer.isBuffer(privateKey)) {
1952
1991
  const privateKey1 = await derToPrivateKey(privateKey);
1953
- return KeyObject4.from(privateKey1);
1992
+ return KeyObject.from(privateKey1);
1954
1993
  } else if (typeof privateKey === "string") {
1955
1994
  try {
1956
1995
  const privateKey1 = await pemToPrivateKey(privateKey);
1957
- return KeyObject4.from(privateKey1);
1996
+ return KeyObject.from(privateKey1);
1958
1997
  } catch (err) {
1959
1998
  doDebug4 && console.log(privateKey);
1960
1999
  throw err;
1961
2000
  }
1962
- } else if (privateKey instanceof KeyObject4) {
2001
+ } else if (isKeyObject(privateKey)) {
1963
2002
  return privateKey;
1964
2003
  }
1965
2004
  throw new Error("Invalid privateKey");
1966
2005
  }
1967
2006
 
1968
- // source/x509/_get_attributes.ts
1969
- var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1970
- var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
1971
- function getAttributes(purpose) {
1972
- let basicConstraints;
1973
- let keyUsageExtension = [];
1974
- let usages;
1975
- let nsComment;
1976
- let extension;
1977
- switch (purpose) {
1978
- case 1 /* ForCertificateAuthority */:
1979
- extension = "v3_ca";
1980
- basicConstraints = new x5092.BasicConstraintsExtension(true, void 0, false);
1981
- usages = keyUsageCA;
1982
- keyUsageExtension = [];
1983
- nsComment = "Self-signed certificate for CA generated by Node-OPCUA Certificate utility V2";
1984
- break;
1985
- case 2 /* ForApplication */:
1986
- case 3 /* ForUserAuthentication */:
1987
- default:
1988
- extension = "v3_selfsigned";
1989
- basicConstraints = new x5092.BasicConstraintsExtension(false, void 0, true);
1990
- usages = keyUsageApplication;
1991
- keyUsageExtension = [x5092.ExtendedKeyUsage.serverAuth, x5092.ExtendedKeyUsage.clientAuth];
1992
- nsComment = "Self-signed certificate generated by Node-OPCUA Certificate utility V2";
1993
- break;
1994
- }
1995
- return { nsComment, basicConstraints, keyUsageExtension, usages };
1996
- }
1997
-
1998
2007
  // source/x509/_build_public_key.ts
1999
2008
  async function buildPublicKey(privateKey) {
2000
2009
  const crypto3 = getCrypto();
@@ -2017,6 +2026,36 @@ async function buildPublicKey(privateKey) {
2017
2026
  return publicKey;
2018
2027
  }
2019
2028
 
2029
+ // source/x509/_get_attributes.ts
2030
+ var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
2031
+ var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
2032
+ function getAttributes(purpose) {
2033
+ let basicConstraints;
2034
+ let keyUsageExtension = [];
2035
+ let usages;
2036
+ let nsComment;
2037
+ let _extension;
2038
+ switch (purpose) {
2039
+ case 1 /* ForCertificateAuthority */:
2040
+ _extension = "v3_ca";
2041
+ basicConstraints = new x5092.BasicConstraintsExtension(true, void 0, false);
2042
+ usages = keyUsageCA;
2043
+ keyUsageExtension = [];
2044
+ nsComment = "Self-signed certificate for CA generated by Node-OPCUA Certificate utility V2";
2045
+ break;
2046
+ // case CertificatePurpose.ForApplication:
2047
+ // case CertificatePurpose.ForUserAuthentication:
2048
+ default:
2049
+ _extension = "v3_selfsigned";
2050
+ basicConstraints = new x5092.BasicConstraintsExtension(false, void 0, true);
2051
+ usages = keyUsageApplication;
2052
+ keyUsageExtension = [x5092.ExtendedKeyUsage.serverAuth, x5092.ExtendedKeyUsage.clientAuth];
2053
+ nsComment = "Self-signed certificate generated by Node-OPCUA Certificate utility V2";
2054
+ break;
2055
+ }
2056
+ return { nsComment, basicConstraints, keyUsageExtension, usages };
2057
+ }
2058
+
2020
2059
  // source/x509/create_certificate_signing_request.ts
2021
2060
  async function createCertificateSigningRequest({
2022
2061
  privateKey,
@@ -2040,9 +2079,15 @@ async function createCertificateSigningRequest({
2040
2079
  publicKey
2041
2080
  };
2042
2081
  const alternativeNameExtensions = [];
2043
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
2044
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
2045
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
2082
+ for (const d of dns ?? []) {
2083
+ alternativeNameExtensions.push({ type: "dns", value: d });
2084
+ }
2085
+ for (const d of ip ?? []) {
2086
+ alternativeNameExtensions.push({ type: "ip", value: d });
2087
+ }
2088
+ if (applicationUri) {
2089
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
2090
+ }
2046
2091
  const { basicConstraints, usages } = getAttributes(purpose);
2047
2092
  const s = new Subject(subject || "");
2048
2093
  const s1 = s.toStringInternal(", ");
@@ -2195,7 +2240,7 @@ var BufferSourceConverter = class _BufferSourceConverter {
2195
2240
  }
2196
2241
  };
2197
2242
  var STRING_TYPE = "string";
2198
- var HEX_REGEX = /^[0-9a-f]+$/i;
2243
+ var HEX_REGEX = /^[0-9a-f\s]+$/i;
2199
2244
  var BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2200
2245
  var BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
2201
2246
  var Utf8Converter = class {
@@ -2643,19 +2688,19 @@ var BIT_STRING_NAME = "BIT STRING";
2643
2688
  function HexBlock(BaseClass) {
2644
2689
  var _a2;
2645
2690
  return _a2 = class Some extends BaseClass {
2646
- constructor(...args) {
2647
- var _a3;
2648
- super(...args);
2649
- const params = args[0] || {};
2650
- this.isHexOnly = (_a3 = params.isHexOnly) !== null && _a3 !== void 0 ? _a3 : false;
2651
- this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2652
- }
2653
2691
  get valueHex() {
2654
2692
  return this.valueHexView.slice().buffer;
2655
2693
  }
2656
2694
  set valueHex(value) {
2657
2695
  this.valueHexView = new Uint8Array(value);
2658
2696
  }
2697
+ constructor(...args) {
2698
+ var _b;
2699
+ super(...args);
2700
+ const params = args[0] || {};
2701
+ this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false;
2702
+ this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2703
+ }
2659
2704
  fromBER(inputBuffer, inputOffset, inputLength) {
2660
2705
  const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
2661
2706
  if (!checkBufferParams(this, view, inputOffset, inputLength)) {
@@ -2690,12 +2735,6 @@ function HexBlock(BaseClass) {
2690
2735
  }, _a2.NAME = "hexBlock", _a2;
2691
2736
  }
2692
2737
  var LocalBaseBlock = class {
2693
- constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2694
- this.blockLength = blockLength;
2695
- this.error = error;
2696
- this.warnings = warnings;
2697
- this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2698
- }
2699
2738
  static blockName() {
2700
2739
  return this.NAME;
2701
2740
  }
@@ -2705,6 +2744,12 @@ var LocalBaseBlock = class {
2705
2744
  set valueBeforeDecode(value) {
2706
2745
  this.valueBeforeDecodeView = new Uint8Array(value);
2707
2746
  }
2747
+ constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2748
+ this.blockLength = blockLength;
2749
+ this.error = error;
2750
+ this.warnings = warnings;
2751
+ this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2752
+ }
2708
2753
  toJSON() {
2709
2754
  return {
2710
2755
  blockName: this.constructor.NAME,
@@ -2717,10 +2762,10 @@ var LocalBaseBlock = class {
2717
2762
  };
2718
2763
  LocalBaseBlock.NAME = "baseBlock";
2719
2764
  var ValueBlock = class extends LocalBaseBlock {
2720
- fromBER(inputBuffer, inputOffset, inputLength) {
2765
+ fromBER(_inputBuffer, _inputOffset, _inputLength) {
2721
2766
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2722
2767
  }
2723
- toBER(sizeOnly, writer) {
2768
+ toBER(_sizeOnly, _writer) {
2724
2769
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2725
2770
  }
2726
2771
  };
@@ -3061,7 +3106,9 @@ var BaseBlock = class extends LocalBaseBlock {
3061
3106
  return Convert.ToHex(this.toBER());
3062
3107
  }
3063
3108
  onAsciiEncoding() {
3064
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;
3109
+ const name = this.constructor.NAME;
3110
+ const value = Convert.ToHex(this.valueBlock.valueBeforeDecodeView);
3111
+ return `${name} : ${value}`;
3065
3112
  }
3066
3113
  isEqual(other) {
3067
3114
  if (this === other) {
@@ -3077,6 +3124,7 @@ var BaseBlock = class extends LocalBaseBlock {
3077
3124
  };
3078
3125
  BaseBlock.NAME = "BaseBlock";
3079
3126
  function prepareIndefiniteForm(baseBlock) {
3127
+ var _a2;
3080
3128
  if (baseBlock instanceof typeStore.Constructed) {
3081
3129
  for (const value of baseBlock.valueBlock.value) {
3082
3130
  if (prepareIndefiniteForm(value)) {
@@ -3084,21 +3132,21 @@ function prepareIndefiniteForm(baseBlock) {
3084
3132
  }
3085
3133
  }
3086
3134
  }
3087
- return !!baseBlock.lenBlock.isIndefiniteForm;
3135
+ return !!((_a2 = baseBlock.lenBlock) === null || _a2 === void 0 ? void 0 : _a2.isIndefiniteForm);
3088
3136
  }
3089
3137
  var BaseStringBlock = class extends BaseBlock {
3090
- constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3091
- super(parameters, stringValueBlockType);
3092
- if (value) {
3093
- this.fromString(value);
3094
- }
3095
- }
3096
3138
  getValue() {
3097
3139
  return this.valueBlock.value;
3098
3140
  }
3099
3141
  setValue(value) {
3100
3142
  this.valueBlock.value = value;
3101
3143
  }
3144
+ constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3145
+ super(parameters, stringValueBlockType);
3146
+ if (value) {
3147
+ this.fromString(value);
3148
+ }
3149
+ }
3102
3150
  fromBER(inputBuffer, inputOffset, inputLength) {
3103
3151
  const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
3104
3152
  if (resultOffset === -1) {
@@ -3457,10 +3505,10 @@ _a$v = Constructed;
3457
3505
  })();
3458
3506
  Constructed.NAME = "CONSTRUCTED";
3459
3507
  var LocalEndOfContentValueBlock = class extends ValueBlock {
3460
- fromBER(inputBuffer, inputOffset, inputLength) {
3508
+ fromBER(inputBuffer, inputOffset, _inputLength) {
3461
3509
  return inputOffset;
3462
3510
  }
3463
- toBER(sizeOnly) {
3511
+ toBER(_sizeOnly) {
3464
3512
  return EMPTY_BUFFER;
3465
3513
  }
3466
3514
  };
@@ -3521,17 +3569,6 @@ _a$t = Null;
3521
3569
  })();
3522
3570
  Null.NAME = "NULL";
3523
3571
  var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3524
- constructor({ value, ...parameters } = {}) {
3525
- super(parameters);
3526
- if (parameters.valueHex) {
3527
- this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3528
- } else {
3529
- this.valueHexView = new Uint8Array(1);
3530
- }
3531
- if (value) {
3532
- this.value = value;
3533
- }
3534
- }
3535
3572
  get value() {
3536
3573
  for (const octet of this.valueHexView) {
3537
3574
  if (octet > 0) {
@@ -3543,6 +3580,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3543
3580
  set value(value) {
3544
3581
  this.valueHexView[0] = value ? 255 : 0;
3545
3582
  }
3583
+ constructor({ value, ...parameters } = {}) {
3584
+ super(parameters);
3585
+ if (parameters.valueHex) {
3586
+ this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3587
+ } else {
3588
+ this.valueHexView = new Uint8Array(1);
3589
+ }
3590
+ if (value) {
3591
+ this.value = value;
3592
+ }
3593
+ }
3546
3594
  fromBER(inputBuffer, inputOffset, inputLength) {
3547
3595
  const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
3548
3596
  if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
@@ -3569,17 +3617,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3569
3617
  LocalBooleanValueBlock.NAME = "BooleanValueBlock";
3570
3618
  var _a$s;
3571
3619
  var Boolean = class extends BaseBlock {
3572
- constructor(parameters = {}) {
3573
- super(parameters, LocalBooleanValueBlock);
3574
- this.idBlock.tagClass = 1;
3575
- this.idBlock.tagNumber = 1;
3576
- }
3577
3620
  getValue() {
3578
3621
  return this.valueBlock.value;
3579
3622
  }
3580
3623
  setValue(value) {
3581
3624
  this.valueBlock.value = value;
3582
3625
  }
3626
+ constructor(parameters = {}) {
3627
+ super(parameters, LocalBooleanValueBlock);
3628
+ this.idBlock.tagClass = 1;
3629
+ this.idBlock.tagNumber = 1;
3630
+ }
3583
3631
  onAsciiEncoding() {
3584
3632
  return `${this.constructor.NAME} : ${this.getValue}`;
3585
3633
  }
@@ -3637,7 +3685,7 @@ var LocalOctetStringValueBlock = class extends HexBlock(LocalConstructedValueBlo
3637
3685
  };
3638
3686
  LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
3639
3687
  var _a$r;
3640
- var OctetString = class _OctetString extends BaseBlock {
3688
+ var OctetString = class extends BaseBlock {
3641
3689
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
3642
3690
  var _b, _c;
3643
3691
  (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length);
@@ -3675,7 +3723,7 @@ var OctetString = class _OctetString extends BaseBlock {
3675
3723
  this.valueBlock.value = [asn.result];
3676
3724
  }
3677
3725
  }
3678
- } catch (e) {
3726
+ } catch {
3679
3727
  }
3680
3728
  }
3681
3729
  return super.fromBER(inputBuffer, inputOffset, inputLength);
@@ -3684,7 +3732,9 @@ var OctetString = class _OctetString extends BaseBlock {
3684
3732
  if (this.valueBlock.isConstructed || this.valueBlock.value && this.valueBlock.value.length) {
3685
3733
  return Constructed.prototype.onAsciiEncoding.call(this);
3686
3734
  }
3687
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueHexView)}`;
3735
+ const name = this.constructor.NAME;
3736
+ const value = Convert.ToHex(this.valueBlock.valueHexView);
3737
+ return `${name} : ${value}`;
3688
3738
  }
3689
3739
  getValue() {
3690
3740
  if (!this.idBlock.isConstructed) {
@@ -3692,7 +3742,7 @@ var OctetString = class _OctetString extends BaseBlock {
3692
3742
  }
3693
3743
  const array = [];
3694
3744
  for (const content of this.valueBlock.value) {
3695
- if (content instanceof _OctetString) {
3745
+ if (content instanceof _a$r) {
3696
3746
  array.push(content.valueBlock.valueHexView);
3697
3747
  }
3698
3748
  }
@@ -3762,7 +3812,7 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3762
3812
  this.value = [asn.result];
3763
3813
  }
3764
3814
  }
3765
- } catch (e) {
3815
+ } catch {
3766
3816
  }
3767
3817
  }
3768
3818
  this.valueHexView = intBuffer.subarray(1);
@@ -3777,7 +3827,9 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3777
3827
  return new ArrayBuffer(this.valueHexView.byteLength + 1);
3778
3828
  }
3779
3829
  if (!this.valueHexView.byteLength) {
3780
- return EMPTY_BUFFER;
3830
+ const empty = new Uint8Array(1);
3831
+ empty[0] = 0;
3832
+ return empty.buffer;
3781
3833
  }
3782
3834
  const retView = new Uint8Array(this.valueHexView.length + 1);
3783
3835
  retView[0] = this.unusedBits;
@@ -3827,7 +3879,9 @@ var BitString = class extends BaseBlock {
3827
3879
  bits.push(byte.toString(2).padStart(8, "0"));
3828
3880
  }
3829
3881
  const bitsStr = bits.join("");
3830
- return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;
3882
+ const name = this.constructor.NAME;
3883
+ const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits);
3884
+ return `${name} : ${value}`;
3831
3885
  }
3832
3886
  }
3833
3887
  };
@@ -3924,16 +3978,6 @@ function viewSub(first, second) {
3924
3978
  return firstViewCopy.slice();
3925
3979
  }
3926
3980
  var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3927
- constructor({ value, ...parameters } = {}) {
3928
- super(parameters);
3929
- this._valueDec = 0;
3930
- if (parameters.valueHex) {
3931
- this.setValueHex();
3932
- }
3933
- if (value !== void 0) {
3934
- this.valueDec = value;
3935
- }
3936
- }
3937
3981
  setValueHex() {
3938
3982
  if (this.valueHexView.length >= 4) {
3939
3983
  this.warnings.push("Too big Integer for decoding, hex only");
@@ -3946,6 +3990,16 @@ var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3946
3990
  }
3947
3991
  }
3948
3992
  }
3993
+ constructor({ value, ...parameters } = {}) {
3994
+ super(parameters);
3995
+ this._valueDec = 0;
3996
+ if (parameters.valueHex) {
3997
+ this.setValueHex();
3998
+ }
3999
+ if (value !== void 0) {
4000
+ this.valueDec = value;
4001
+ }
4002
+ }
3949
4003
  set valueDec(v) {
3950
4004
  this._valueDec = v;
3951
4005
  this.isHexOnly = false;
@@ -4058,7 +4112,7 @@ LocalIntegerValueBlock.NAME = "IntegerValueBlock";
4058
4112
  });
4059
4113
  })();
4060
4114
  var _a$o;
4061
- var Integer = class _Integer extends BaseBlock {
4115
+ var Integer = class extends BaseBlock {
4062
4116
  constructor(parameters = {}) {
4063
4117
  super(parameters, LocalIntegerValueBlock);
4064
4118
  this.idBlock.tagClass = 1;
@@ -4088,18 +4142,16 @@ var Integer = class _Integer extends BaseBlock {
4088
4142
  }
4089
4143
  writer.write(view);
4090
4144
  }
4091
- const res = new _Integer({
4092
- valueHex: writer.final()
4093
- });
4145
+ const res = new _a$o({ valueHex: writer.final() });
4094
4146
  return res;
4095
4147
  }
4096
4148
  convertToDER() {
4097
- const integer = new _Integer({ valueHex: this.valueBlock.valueHexView });
4149
+ const integer = new _a$o({ valueHex: this.valueBlock.valueHexView });
4098
4150
  integer.valueBlock.toDER();
4099
4151
  return integer;
4100
4152
  }
4101
4153
  convertFromDER() {
4102
- return new _Integer({
4154
+ return new _a$o({
4103
4155
  valueHex: this.valueBlock.valueHexView[0] === 0 ? this.valueBlock.valueHexView.subarray(1) : this.valueBlock.valueHexView
4104
4156
  });
4105
4157
  }
@@ -4362,17 +4414,17 @@ var LocalObjectIdentifierValueBlock = class extends ValueBlock {
4362
4414
  LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
4363
4415
  var _a$m;
4364
4416
  var ObjectIdentifier = class extends BaseBlock {
4365
- constructor(parameters = {}) {
4366
- super(parameters, LocalObjectIdentifierValueBlock);
4367
- this.idBlock.tagClass = 1;
4368
- this.idBlock.tagNumber = 6;
4369
- }
4370
4417
  getValue() {
4371
4418
  return this.valueBlock.toString();
4372
4419
  }
4373
4420
  setValue(value) {
4374
4421
  this.valueBlock.fromString(value);
4375
4422
  }
4423
+ constructor(parameters = {}) {
4424
+ super(parameters, LocalObjectIdentifierValueBlock);
4425
+ this.idBlock.tagClass = 1;
4426
+ this.idBlock.tagNumber = 6;
4427
+ }
4376
4428
  onAsciiEncoding() {
4377
4429
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4378
4430
  }
@@ -4492,7 +4544,7 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4492
4544
  }
4493
4545
  return resultOffset;
4494
4546
  }
4495
- toBER(sizeOnly, writer) {
4547
+ toBER(sizeOnly, _writer) {
4496
4548
  const retBuffers = [];
4497
4549
  for (let i = 0; i < this.value.length; i++) {
4498
4550
  const valueBuf = this.value[i].toBER(sizeOnly);
@@ -4554,17 +4606,17 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4554
4606
  LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
4555
4607
  var _a$l;
4556
4608
  var RelativeObjectIdentifier = class extends BaseBlock {
4557
- constructor(parameters = {}) {
4558
- super(parameters, LocalRelativeObjectIdentifierValueBlock);
4559
- this.idBlock.tagClass = 1;
4560
- this.idBlock.tagNumber = 13;
4561
- }
4562
4609
  getValue() {
4563
4610
  return this.valueBlock.toString();
4564
4611
  }
4565
4612
  setValue(value) {
4566
4613
  this.valueBlock.fromString(value);
4567
4614
  }
4615
+ constructor(parameters = {}) {
4616
+ super(parameters, LocalRelativeObjectIdentifierValueBlock);
4617
+ this.idBlock.tagClass = 1;
4618
+ this.idBlock.tagNumber = 13;
4619
+ }
4568
4620
  onAsciiEncoding() {
4569
4621
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4570
4622
  }
@@ -4961,7 +5013,8 @@ var GeneralizedTime = class extends UTCTime {
4961
5013
  this.millisecond = inputDate.getUTCMilliseconds();
4962
5014
  }
4963
5015
  toDate() {
4964
- return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond));
5016
+ const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond);
5017
+ return new Date(utcDate);
4965
5018
  }
4966
5019
  fromString(inputString) {
4967
5020
  let isUTC = false;
@@ -5210,28 +5263,28 @@ var Repeated = class extends Any {
5210
5263
  }
5211
5264
  };
5212
5265
  var RawData = class {
5213
- constructor({ data = EMPTY_VIEW } = {}) {
5214
- this.dataView = BufferSourceConverter.toUint8Array(data);
5215
- }
5216
5266
  get data() {
5217
5267
  return this.dataView.slice().buffer;
5218
5268
  }
5219
5269
  set data(value) {
5220
5270
  this.dataView = BufferSourceConverter.toUint8Array(value);
5221
5271
  }
5272
+ constructor({ data = EMPTY_VIEW } = {}) {
5273
+ this.dataView = BufferSourceConverter.toUint8Array(data);
5274
+ }
5222
5275
  fromBER(inputBuffer, inputOffset, inputLength) {
5223
5276
  const endLength = inputOffset + inputLength;
5224
5277
  this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
5225
5278
  return endLength;
5226
5279
  }
5227
- toBER(sizeOnly) {
5280
+ toBER(_sizeOnly) {
5228
5281
  return this.dataView.slice().buffer;
5229
5282
  }
5230
5283
  };
5231
5284
  function compareSchema(root, inputData, inputSchema) {
5232
5285
  if (inputSchema instanceof Choice) {
5233
- for (let j = 0; j < inputSchema.value.length; j++) {
5234
- const result = compareSchema(root, inputData, inputSchema.value[j]);
5286
+ for (const element of inputSchema.value) {
5287
+ const result = compareSchema(root, inputData, element);
5235
5288
  if (result.verified) {
5236
5289
  return {
5237
5290
  verified: true,
@@ -5242,9 +5295,7 @@ function compareSchema(root, inputData, inputSchema) {
5242
5295
  {
5243
5296
  const _result = {
5244
5297
  verified: false,
5245
- result: {
5246
- error: "Wrong values for Choice type"
5247
- }
5298
+ result: { error: "Wrong values for Choice type" }
5248
5299
  };
5249
5300
  if (inputSchema.hasOwnProperty(NAME))
5250
5301
  _result.name = inputSchema.name;
@@ -5390,9 +5441,7 @@ function compareSchema(root, inputData, inputSchema) {
5390
5441
  let admission = 0;
5391
5442
  let result = {
5392
5443
  verified: false,
5393
- result: {
5394
- error: "Unknown error"
5395
- }
5444
+ result: { error: "Unknown error" }
5396
5445
  };
5397
5446
  let maxLength = inputSchema.valueBlock.value.length;
5398
5447
  if (maxLength > 0) {
@@ -5769,10 +5818,7 @@ var AsnSchemaStorage = class {
5769
5818
  }
5770
5819
  }
5771
5820
  createDefault(target) {
5772
- const schema = {
5773
- type: AsnTypeTypes.Sequence,
5774
- items: {}
5775
- };
5821
+ const schema = { type: AsnTypeTypes.Sequence, items: {} };
5776
5822
  const parentSchema = this.findParentSchema(target);
5777
5823
  if (parentSchema) {
5778
5824
  Object.assign(schema, parentSchema);
@@ -5814,26 +5860,14 @@ var AsnSchemaStorage = class {
5814
5860
  const Container = item.repeated === "set" ? Set : Sequence;
5815
5861
  asn1Item = new Container({
5816
5862
  name: "",
5817
- value: [
5818
- new Repeated({
5819
- name,
5820
- value: asn1Item
5821
- })
5822
- ]
5863
+ value: [new Repeated({ name, value: asn1Item })]
5823
5864
  });
5824
5865
  }
5825
5866
  if (item.context !== null && item.context !== void 0) {
5826
5867
  if (item.implicit) {
5827
5868
  if (typeof item.type === "number" || isConvertible(item.type)) {
5828
5869
  const Container = item.repeated ? Constructed : Primitive;
5829
- asn1Value.push(new Container({
5830
- name,
5831
- optional,
5832
- idBlock: {
5833
- tagClass: 3,
5834
- tagNumber: item.context
5835
- }
5836
- }));
5870
+ asn1Value.push(new Container({ name, optional, idBlock: { tagClass: 3, tagNumber: item.context } }));
5837
5871
  } else {
5838
5872
  this.cache(item.type);
5839
5873
  const isRepeated = !!item.repeated;
@@ -5842,20 +5876,14 @@ var AsnSchemaStorage = class {
5842
5876
  asn1Value.push(new Constructed({
5843
5877
  name: !isRepeated ? name : "",
5844
5878
  optional,
5845
- idBlock: {
5846
- tagClass: 3,
5847
- tagNumber: item.context
5848
- },
5879
+ idBlock: { tagClass: 3, tagNumber: item.context },
5849
5880
  value
5850
5881
  }));
5851
5882
  }
5852
5883
  } else {
5853
5884
  asn1Value.push(new Constructed({
5854
5885
  optional,
5855
- idBlock: {
5856
- tagClass: 3,
5857
- tagNumber: item.context
5858
- },
5886
+ idBlock: { tagClass: 3, tagNumber: item.context },
5859
5887
  value: [asn1Item]
5860
5888
  }));
5861
5889
  }
@@ -5911,7 +5939,6 @@ var AsnParser = class {
5911
5939
  return res;
5912
5940
  }
5913
5941
  static fromASN(asn1Schema, target) {
5914
- var _a2;
5915
5942
  try {
5916
5943
  if (isConvertible(target)) {
5917
5944
  const value = new target();
@@ -5920,104 +5947,259 @@ var AsnParser = class {
5920
5947
  const schema = schemaStorage.get(target);
5921
5948
  schemaStorage.cache(target);
5922
5949
  let targetSchema = schema.schema;
5923
- if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
5924
- targetSchema = new Constructed({
5925
- idBlock: {
5926
- tagClass: 3,
5927
- tagNumber: asn1Schema.idBlock.tagNumber
5928
- },
5929
- value: schema.schema.valueBlock.value
5930
- });
5931
- for (const key in schema.items) {
5932
- delete asn1Schema[key];
5933
- }
5950
+ const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema);
5951
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.result) {
5952
+ return choiceResult.result;
5934
5953
  }
5935
- const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
5936
- if (!asn1ComparedSchema.verified) {
5937
- throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`);
5954
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.targetSchema) {
5955
+ targetSchema = choiceResult.targetSchema;
5938
5956
  }
5957
+ const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
5939
5958
  const res = new target();
5940
5959
  if (isTypeOfArray(target)) {
5941
- if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
5942
- throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
5943
- }
5944
- const itemType = schema.itemType;
5945
- if (typeof itemType === "number") {
5946
- const converter = defaultConverter(itemType);
5947
- if (!converter) {
5948
- throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
5949
- }
5950
- return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
5951
- } else {
5952
- return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
5953
- }
5960
+ return this.handleArrayTypes(asn1Schema, schema, target);
5961
+ }
5962
+ this.processSchemaItems(schema, sequenceResult, res);
5963
+ return res;
5964
+ } catch (error) {
5965
+ if (error instanceof AsnSchemaValidationError) {
5966
+ error.schemas.push(target.name);
5954
5967
  }
5968
+ throw error;
5969
+ }
5970
+ }
5971
+ static handleChoiceTypes(asn1Schema, schema, target, targetSchema) {
5972
+ if (asn1Schema.constructor === Constructed && schema.type === AsnTypeTypes.Choice && asn1Schema.idBlock.tagClass === 3) {
5955
5973
  for (const key in schema.items) {
5956
- const asn1SchemaValue = asn1ComparedSchema.result[key];
5957
- if (!asn1SchemaValue) {
5958
- continue;
5959
- }
5960
5974
  const schemaItem = schema.items[key];
5961
- const schemaItemType = schemaItem.type;
5962
- if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
5963
- const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
5964
- if (!converter) {
5965
- throw new Error("Converter is empty");
5966
- }
5967
- if (schemaItem.repeated) {
5968
- if (schemaItem.implicit) {
5969
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
5970
- const newItem = new Container();
5971
- newItem.valueBlock = asn1SchemaValue.valueBlock;
5972
- const newItemAsn = fromBER(newItem.toBER(false));
5973
- if (newItemAsn.offset === -1) {
5974
- throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
5975
- }
5976
- if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
5977
- throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
5978
- }
5979
- const value = newItemAsn.result.valueBlock.value;
5980
- res[key] = Array.from(value, (element) => converter.fromASN(element));
5981
- } else {
5982
- res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
5983
- }
5984
- } else {
5985
- let value = asn1SchemaValue;
5986
- if (schemaItem.implicit) {
5987
- let newItem;
5988
- if (isConvertible(schemaItemType)) {
5989
- newItem = new schemaItemType().toSchema("");
5990
- } else {
5991
- const Asn1TypeName = AsnPropTypes[schemaItemType];
5992
- const Asn1Type = index_es_exports[Asn1TypeName];
5993
- if (!Asn1Type) {
5994
- throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
5995
- }
5996
- newItem = new Asn1Type();
5975
+ if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
5976
+ if (typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type)) {
5977
+ const fieldSchema = schemaStorage.get(schemaItem.type);
5978
+ if (fieldSchema && fieldSchema.type === AsnTypeTypes.Sequence) {
5979
+ const newSeq = new Sequence();
5980
+ if ("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value) && "value" in newSeq.valueBlock) {
5981
+ newSeq.valueBlock.value = asn1Schema.valueBlock.value;
5982
+ const fieldValue = this.fromASN(newSeq, schemaItem.type);
5983
+ const res = new target();
5984
+ res[key] = fieldValue;
5985
+ return { result: res };
5997
5986
  }
5998
- newItem.valueBlock = value.valueBlock;
5999
- value = fromBER(newItem.toBER(false)).result;
6000
5987
  }
6001
- res[key] = converter.fromASN(value);
6002
5988
  }
6003
- } else {
6004
- if (schemaItem.repeated) {
6005
- if (!Array.isArray(asn1SchemaValue)) {
6006
- throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
6007
- }
6008
- res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
6009
- } else {
6010
- res[key] = this.fromASN(asn1SchemaValue, schemaItemType);
5989
+ }
5990
+ }
5991
+ } else if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
5992
+ const newTargetSchema = new Constructed({
5993
+ idBlock: {
5994
+ tagClass: 3,
5995
+ tagNumber: asn1Schema.idBlock.tagNumber
5996
+ },
5997
+ value: schema.schema.valueBlock.value
5998
+ });
5999
+ for (const key in schema.items) {
6000
+ delete asn1Schema[key];
6001
+ }
6002
+ return { targetSchema: newTargetSchema };
6003
+ }
6004
+ return null;
6005
+ }
6006
+ static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
6007
+ if (schema.type === AsnTypeTypes.Sequence) {
6008
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
6009
+ if (!asn1ComparedSchema.verified) {
6010
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
6011
+ }
6012
+ return asn1ComparedSchema;
6013
+ } else {
6014
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
6015
+ if (!asn1ComparedSchema.verified) {
6016
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
6017
+ }
6018
+ return asn1ComparedSchema;
6019
+ }
6020
+ }
6021
+ static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
6022
+ let elementsToProcess = asn1Elements.slice(asn1Index);
6023
+ if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
6024
+ const seq = elementsToProcess[0];
6025
+ if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
6026
+ elementsToProcess = seq.valueBlock.value;
6027
+ }
6028
+ }
6029
+ if (typeof schemaItem.type === "number") {
6030
+ const converter = defaultConverter(schemaItem.type);
6031
+ if (!converter)
6032
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
6033
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
6034
+ try {
6035
+ return converter.fromASN(el);
6036
+ } catch {
6037
+ return void 0;
6038
+ }
6039
+ }).filter((v) => v !== void 0);
6040
+ } else {
6041
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
6042
+ try {
6043
+ return this.fromASN(el, schemaItem.type);
6044
+ } catch {
6045
+ return void 0;
6046
+ }
6047
+ }).filter((v) => v !== void 0);
6048
+ }
6049
+ }
6050
+ static processPrimitiveField(asn1Element, schemaItem) {
6051
+ const converter = defaultConverter(schemaItem.type);
6052
+ if (!converter)
6053
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
6054
+ return converter.fromASN(asn1Element);
6055
+ }
6056
+ static isOptionalChoiceField(schemaItem) {
6057
+ return schemaItem.optional && typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type) && schemaStorage.get(schemaItem.type).type === AsnTypeTypes.Choice;
6058
+ }
6059
+ static processOptionalChoiceField(asn1Element, schemaItem) {
6060
+ try {
6061
+ const value = this.fromASN(asn1Element, schemaItem.type);
6062
+ return { processed: true, value };
6063
+ } catch (err) {
6064
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
6065
+ return { processed: false };
6066
+ }
6067
+ throw err;
6068
+ }
6069
+ }
6070
+ static handleArrayTypes(asn1Schema, schema, target) {
6071
+ if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
6072
+ throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
6073
+ }
6074
+ const itemType = schema.itemType;
6075
+ if (typeof itemType === "number") {
6076
+ const converter = defaultConverter(itemType);
6077
+ if (!converter) {
6078
+ throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
6079
+ }
6080
+ return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
6081
+ } else {
6082
+ return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
6083
+ }
6084
+ }
6085
+ static processSchemaItems(schema, asn1ComparedSchema, res) {
6086
+ for (const key in schema.items) {
6087
+ const asn1SchemaValue = asn1ComparedSchema.result[key];
6088
+ if (!asn1SchemaValue) {
6089
+ continue;
6090
+ }
6091
+ const schemaItem = schema.items[key];
6092
+ const schemaItemType = schemaItem.type;
6093
+ let parsedValue;
6094
+ if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
6095
+ parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6096
+ } else {
6097
+ parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6098
+ }
6099
+ if (parsedValue && typeof parsedValue === "object" && "value" in parsedValue && "raw" in parsedValue) {
6100
+ res[key] = parsedValue.value;
6101
+ res[`${key}Raw`] = parsedValue.raw;
6102
+ } else {
6103
+ res[key] = parsedValue;
6104
+ }
6105
+ }
6106
+ }
6107
+ static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6108
+ var _a2;
6109
+ const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
6110
+ if (!converter) {
6111
+ throw new Error("Converter is empty");
6112
+ }
6113
+ if (schemaItem.repeated) {
6114
+ return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter);
6115
+ } else {
6116
+ return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter);
6117
+ }
6118
+ }
6119
+ static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter) {
6120
+ if (schemaItem.implicit) {
6121
+ const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
6122
+ const newItem = new Container();
6123
+ newItem.valueBlock = asn1SchemaValue.valueBlock;
6124
+ const newItemAsn = fromBER(newItem.toBER(false));
6125
+ if (newItemAsn.offset === -1) {
6126
+ throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
6127
+ }
6128
+ if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
6129
+ throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
6130
+ }
6131
+ const value = newItemAsn.result.valueBlock.value;
6132
+ return Array.from(value, (element) => converter.fromASN(element));
6133
+ } else {
6134
+ return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
6135
+ }
6136
+ }
6137
+ static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter) {
6138
+ let value = asn1SchemaValue;
6139
+ if (schemaItem.implicit) {
6140
+ let newItem;
6141
+ if (isConvertible(schemaItemType)) {
6142
+ newItem = new schemaItemType().toSchema("");
6143
+ } else {
6144
+ const Asn1TypeName = AsnPropTypes[schemaItemType];
6145
+ const Asn1Type = index_es_exports[Asn1TypeName];
6146
+ if (!Asn1Type) {
6147
+ throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
6148
+ }
6149
+ newItem = new Asn1Type();
6150
+ }
6151
+ newItem.valueBlock = value.valueBlock;
6152
+ value = fromBER(newItem.toBER(false)).result;
6153
+ }
6154
+ return converter.fromASN(value);
6155
+ }
6156
+ static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6157
+ if (schemaItem.repeated) {
6158
+ if (!Array.isArray(asn1SchemaValue)) {
6159
+ throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
6160
+ }
6161
+ return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
6162
+ } else {
6163
+ const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
6164
+ if (this.isOptionalChoiceField(schemaItem)) {
6165
+ try {
6166
+ return this.fromASN(valueToProcess, schemaItemType);
6167
+ } catch (err) {
6168
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
6169
+ return void 0;
6011
6170
  }
6171
+ throw err;
6172
+ }
6173
+ } else {
6174
+ const parsedValue = this.fromASN(valueToProcess, schemaItemType);
6175
+ if (schemaItem.raw) {
6176
+ return {
6177
+ value: parsedValue,
6178
+ raw: asn1SchemaValue.valueBeforeDecodeView
6179
+ };
6012
6180
  }
6181
+ return parsedValue;
6013
6182
  }
6014
- return res;
6015
- } catch (error) {
6016
- if (error instanceof AsnSchemaValidationError) {
6017
- error.schemas.push(target.name);
6183
+ }
6184
+ }
6185
+ static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
6186
+ if (schemaItem.implicit && typeof schemaItem.context === "number") {
6187
+ const schema = schemaStorage.get(schemaItemType);
6188
+ if (schema.type === AsnTypeTypes.Sequence) {
6189
+ const newSeq = new Sequence();
6190
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSeq.valueBlock) {
6191
+ newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
6192
+ return newSeq;
6193
+ }
6194
+ } else if (schema.type === AsnTypeTypes.Set) {
6195
+ const newSet = new Set();
6196
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSet.valueBlock) {
6197
+ newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
6198
+ return newSet;
6199
+ }
6018
6200
  }
6019
- throw error;
6020
6201
  }
6202
+ return asn1SchemaValue;
6021
6203
  }
6022
6204
  };
6023
6205
 
@@ -6199,9 +6381,19 @@ async function createSelfSignedCertificate({
6199
6381
  }
6200
6382
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6201
6383
  const alternativeNameExtensions = [];
6202
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6203
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6204
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
6384
+ if (dns) {
6385
+ for (const d of dns) {
6386
+ alternativeNameExtensions.push({ type: "dns", value: d });
6387
+ }
6388
+ }
6389
+ if (ip) {
6390
+ for (const d of ip) {
6391
+ alternativeNameExtensions.push({ type: "ip", value: d });
6392
+ }
6393
+ }
6394
+ if (applicationUri) {
6395
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
6396
+ }
6205
6397
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6206
6398
  const s = new Subject(subject || "");
6207
6399
  const s1 = s.toStringInternal(", ");
@@ -6313,7 +6505,7 @@ pvtsutils/build/index.es.js:
6313
6505
  (*!
6314
6506
  * MIT License
6315
6507
  *
6316
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
6508
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
6317
6509
  *
6318
6510
  * Permission is hereby granted, free of charge, to any person obtaining a copy
6319
6511
  * of this software and associated documentation files (the "Software"), to deal