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.
@@ -1,22 +1,37 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
2
  var __export = (target, all) => {
9
3
  for (var name in all)
10
4
  __defProp(target, name, { get: all[name], enumerable: true });
11
5
  };
12
6
 
13
7
  // ../../node_modules/tsup/assets/esm_shims.js
14
- import { fileURLToPath } from "url";
15
8
  import path from "path";
9
+ import { fileURLToPath } from "url";
16
10
  var getFilename = () => fileURLToPath(import.meta.url);
17
11
  var getDirname = () => path.dirname(getFilename());
18
12
  var __dirname = /* @__PURE__ */ getDirname();
19
13
 
14
+ // source/common.ts
15
+ import __crypto from "crypto";
16
+ var KeyObjectOrig = __crypto.KeyObject;
17
+ var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = __crypto;
18
+ function isKeyObject(mayBeKeyObject) {
19
+ if (KeyObjectOrig) {
20
+ return mayBeKeyObject instanceof KeyObjectOrig;
21
+ }
22
+ return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
23
+ }
24
+ var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
25
+ CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
26
+ CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
27
+ CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
28
+ CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
29
+ return CertificatePurpose2;
30
+ })(CertificatePurpose || {});
31
+
32
+ // source/crypto_explore_certificate.ts
33
+ import assert4 from "assert";
34
+
20
35
  // source/asn1.ts
21
36
  import assert from "assert";
22
37
 
@@ -354,7 +369,7 @@ var TagType = /* @__PURE__ */ ((TagType2) => {
354
369
  function readTag(buf, pos) {
355
370
  const start = pos;
356
371
  if (buf.length <= pos) {
357
- throw new Error("Invalid position : buf.length=" + buf.length + " pos =" + pos);
372
+ throw new Error(`Invalid position : buf.length=${buf.length} pos=${pos}`);
358
373
  }
359
374
  const tag = buf.readUInt8(pos);
360
375
  pos += 1;
@@ -383,7 +398,8 @@ function readStruct(buf, blockInfo) {
383
398
  return blocks;
384
399
  }
385
400
  function parseBitString(buffer, start, end, maxLength) {
386
- const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = "(" + lenBit + " bit)\n";
401
+ const unusedBit = buffer.readUInt8(start), lenBit = (end - start - 1 << 3) - unusedBit, intro = `(${lenBit} bit)
402
+ `;
387
403
  let s = "", skip = unusedBit;
388
404
  for (let i = end - 1; i > start; --i) {
389
405
  const b = buffer.readUInt8(i);
@@ -409,7 +425,7 @@ function readBitString(buffer, block) {
409
425
  function formatBuffer2DigitHexWithColum(buffer) {
410
426
  const value = [];
411
427
  for (let i = 0; i < buffer.length; i++) {
412
- value.push(("00" + buffer.readUInt8(i).toString(16)).substr(-2, 2));
428
+ value.push(`00${buffer.readUInt8(i).toString(16)}`.substr(-2, 2));
413
429
  }
414
430
  return value.join(":").toUpperCase().replace(/^(00:)*/, "");
415
431
  }
@@ -446,9 +462,9 @@ function parseOID(buffer, start, end) {
446
462
  if (!(v & 128)) {
447
463
  if (s === "") {
448
464
  const m = n < 80 ? n < 40 ? 0 : 1 : 2;
449
- s = m + "." + (n - m * 40);
465
+ s = `${m}.${n - m * 40}`;
450
466
  } else {
451
- s += "." + n.toString();
467
+ s += `.${n.toString()}`;
452
468
  }
453
469
  n = 0;
454
470
  bits = 0;
@@ -505,11 +521,11 @@ function readIntegerValue(buffer, block) {
505
521
  return value;
506
522
  }
507
523
  function readBooleanValue(buffer, block) {
508
- assert(block.tag === 1 /* BOOLEAN */, "expecting a BOOLEAN tag. got " + TagType[block.tag]);
524
+ assert(block.tag === 1 /* BOOLEAN */, `expecting a BOOLEAN tag. got ${TagType[block.tag]}`);
509
525
  const pos = block.position;
510
526
  const nbBytes = block.length;
511
527
  assert(nbBytes < 4);
512
- const value = buffer.readUInt8(pos) ? true : false;
528
+ const value = !!buffer.readUInt8(pos);
513
529
  return value;
514
530
  }
515
531
  function readVersionValue(buffer, block) {
@@ -561,7 +577,7 @@ function readValue(buffer, block) {
561
577
  case 24 /* GeneralizedTime */:
562
578
  return convertGeneralizedTime(getBlock(buffer, block).toString("ascii"));
563
579
  default:
564
- throw new Error("Invalid tag 0x" + block.tag.toString(16));
580
+ throw new Error(`Invalid tag 0x${block.tag.toString(16)}`);
565
581
  }
566
582
  }
567
583
  function findBlockAtIndex(blocks, index) {
@@ -576,37 +592,235 @@ function readTime(buffer, block) {
576
592
  }
577
593
 
578
594
  // source/crypto_utils.ts
595
+ import assert2 from "assert";
579
596
  import constants from "constants";
580
- import assert4 from "assert";
581
597
  import {
582
598
  createHash,
583
599
  createSign,
584
600
  createVerify,
585
- publicEncrypt as publicEncrypt1,
586
- privateDecrypt as privateDecrypt1
601
+ privateDecrypt as privateDecrypt1,
602
+ publicEncrypt as publicEncrypt1
587
603
  } from "crypto";
588
- import pkg_hexy from "hexy";
604
+ import jsrsasign from "jsrsasign";
589
605
 
590
606
  // source/buffer_utils.ts
591
607
  var createFastUninitializedBuffer = Buffer.allocUnsafe ? Buffer.allocUnsafe : (size) => {
592
608
  return new Buffer(size);
593
609
  };
594
610
 
595
- // source/crypto_explore_certificate.ts
596
- import assert3 from "assert";
611
+ // source/hexy.ts
612
+ function hexy(buffer, { width, format } = {}) {
613
+ width = width || 80;
614
+ if (format === "twos") {
615
+ width = 26 * 3;
616
+ }
617
+ const regex = new RegExp(`.{1,${width}}`, "g");
618
+ const regexTwos = new RegExp(`.{1,${2}}`, "g");
619
+ let fullHex = buffer.toString("hex");
620
+ if (format === "twos") {
621
+ fullHex = fullHex.match(regexTwos)?.join(" ") || "";
622
+ }
623
+ return fullHex.match(regex)?.join("\n") || "";
624
+ }
625
+
626
+ // source/crypto_utils.ts
627
+ var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
628
+ var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
629
+ function identifyPemType(rawKey) {
630
+ if (Buffer.isBuffer(rawKey)) {
631
+ rawKey = rawKey.toString("utf8");
632
+ }
633
+ const match = PEM_TYPE_REGEX.exec(rawKey);
634
+ return !match ? void 0 : match[2];
635
+ }
636
+ function removeTrailingLF(str) {
637
+ const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
638
+ return tmp;
639
+ }
640
+ function toPem(raw_key, pem) {
641
+ assert2(raw_key, "expecting a key");
642
+ assert2(typeof pem === "string");
643
+ let pemType = identifyPemType(raw_key);
644
+ if (pemType) {
645
+ return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
646
+ } else {
647
+ pemType = pem;
648
+ assert2(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
649
+ let b = raw_key.toString("base64");
650
+ let str = `-----BEGIN ${pemType}-----
651
+ `;
652
+ while (b.length) {
653
+ str += `${b.substring(0, 64)}
654
+ `;
655
+ b = b.substring(64);
656
+ }
657
+ str += `-----END ${pemType}-----`;
658
+ return str;
659
+ }
660
+ }
661
+ function convertPEMtoDER(raw_key) {
662
+ let match;
663
+ let _pemType;
664
+ let base64str;
665
+ const parts = [];
666
+ PEM_REGEX.lastIndex = 0;
667
+ match = PEM_REGEX.exec(raw_key);
668
+ while (match !== null) {
669
+ _pemType = match[2];
670
+ base64str = match[3];
671
+ base64str = base64str.replace(/\r?\n/g, "");
672
+ parts.push(Buffer.from(base64str, "base64"));
673
+ match = PEM_REGEX.exec(raw_key);
674
+ }
675
+ return combine_der(parts);
676
+ }
677
+ function hexDump(buffer, width) {
678
+ if (!buffer) {
679
+ return "<>";
680
+ }
681
+ width = width || 32;
682
+ if (buffer.length > 1024) {
683
+ return `${hexy(buffer.subarray(0, 1024), { width, format: "twos" })}
684
+ .... ( ${buffer.length})`;
685
+ } else {
686
+ return hexy(buffer, { width, format: "twos" });
687
+ }
688
+ }
689
+ function makeMessageChunkSignature(chunk, options) {
690
+ const signer = createSign(options.algorithm);
691
+ signer.update(chunk);
692
+ const signature = signer.sign(options.privateKey.hidden);
693
+ assert2(!options.signatureLength || signature.length === options.signatureLength);
694
+ return signature;
695
+ }
696
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
697
+ const verify = createVerify(options.algorithm);
698
+ verify.update(blockToVerify);
699
+ return verify.verify(options.publicKey, signature);
700
+ }
701
+ function makeSHA1Thumbprint(buffer) {
702
+ return createHash("sha1").update(buffer).digest();
703
+ }
704
+ var RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
705
+ var RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
706
+ var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
707
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
708
+ PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
709
+ return PaddingAlgorithm2;
710
+ })(PaddingAlgorithm || {});
711
+ assert2(4 /* RSA_PKCS1_OAEP_PADDING */ === constants.RSA_PKCS1_OAEP_PADDING);
712
+ assert2(1 /* RSA_PKCS1_PADDING */ === constants.RSA_PKCS1_PADDING);
713
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
714
+ if (algorithm === void 0) {
715
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
716
+ }
717
+ return publicEncrypt1(
718
+ {
719
+ key: publicKey,
720
+ padding: algorithm
721
+ },
722
+ buffer
723
+ );
724
+ }
725
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
726
+ if (algorithm === void 0) {
727
+ algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
728
+ }
729
+ try {
730
+ return privateDecrypt1(
731
+ {
732
+ key: privateKey.hidden,
733
+ padding: algorithm
734
+ },
735
+ buffer
736
+ );
737
+ } catch (_err) {
738
+ return Buffer.alloc(1);
739
+ }
740
+ }
741
+ var publicEncrypt = publicEncrypt_native;
742
+ var privateDecrypt = privateDecrypt_native;
743
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
744
+ if (paddingAlgorithm === void 0) {
745
+ paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
746
+ }
747
+ if (paddingAlgorithm === RSA_PKCS1_PADDING) {
748
+ padding = padding || 11;
749
+ if (padding !== 11) throw new Error("padding should be 11");
750
+ } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
751
+ padding = padding || 42;
752
+ if (padding !== 42) throw new Error("padding should be 42");
753
+ } else {
754
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
755
+ }
756
+ const chunk_size = blockSize - padding;
757
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
758
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
759
+ for (let i = 0; i < nbBlocks; i++) {
760
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
761
+ const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
762
+ if (encrypted_chunk.length !== blockSize) {
763
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
764
+ }
765
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
766
+ }
767
+ return outputBuffer;
768
+ }
769
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
770
+ paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
771
+ if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
772
+ throw new Error(`Invalid padding algorithm ${paddingAlgorithm}`);
773
+ }
774
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
775
+ const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
776
+ let total_length = 0;
777
+ for (let i = 0; i < nbBlocks; i++) {
778
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
779
+ const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
780
+ decrypted_buf.copy(outputBuffer, total_length);
781
+ total_length += decrypted_buf.length;
782
+ }
783
+ return outputBuffer.subarray(0, total_length);
784
+ }
785
+ function coerceCertificatePem(certificate) {
786
+ if (Buffer.isBuffer(certificate)) {
787
+ certificate = toPem(certificate, "CERTIFICATE");
788
+ }
789
+ assert2(typeof certificate === "string");
790
+ return certificate;
791
+ }
792
+ function extractPublicKeyFromCertificateSync(certificate) {
793
+ certificate = coerceCertificatePem(certificate);
794
+ const key = jsrsasign.KEYUTIL.getKey(certificate);
795
+ const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
796
+ assert2(typeof publicKeyAsPem === "string");
797
+ return publicKeyAsPem;
798
+ }
799
+ function extractPublicKeyFromCertificate(certificate, callback) {
800
+ let err1 = null;
801
+ let keyPem;
802
+ try {
803
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
804
+ } catch (err) {
805
+ err1 = err;
806
+ }
807
+ setImmediate(() => {
808
+ callback(err1, keyPem);
809
+ });
810
+ }
597
811
 
598
812
  // source/directory_name.ts
599
- import assert2 from "assert";
813
+ import assert3 from "assert";
600
814
  function readDirectoryName(buffer, block) {
601
815
  const set_blocks = readStruct(buffer, block);
602
816
  const names = {};
603
817
  for (const set_block of set_blocks) {
604
- assert2(set_block.tag === 49);
818
+ assert3(set_block.tag === 49);
605
819
  const blocks = readStruct(buffer, set_block);
606
- assert2(blocks.length === 1);
607
- assert2(blocks[0].tag === 48);
820
+ assert3(blocks.length === 1);
821
+ assert3(blocks[0].tag === 48);
608
822
  const sequenceBlock = readStruct(buffer, blocks[0]);
609
- assert2(sequenceBlock.length === 2);
823
+ assert3(sequenceBlock.length === 2);
610
824
  const type = readObjectIdentifier(buffer, sequenceBlock[0]);
611
825
  names[type.name] = readValue(buffer, sequenceBlock[1]);
612
826
  }
@@ -686,7 +900,7 @@ function _readAuthorityKeyIdentifier(buffer) {
686
900
  // can be null for self-signed certf
687
901
  };
688
902
  }
689
- function readBasicConstraint2_5_29_19(buffer, block) {
903
+ function readBasicConstraint2_5_29_19(buffer, _block) {
690
904
  const block_info = readTag(buffer, 0);
691
905
  const inner_blocks = readStruct(buffer, block_info).slice(0, 2);
692
906
  let cA = false;
@@ -731,14 +945,14 @@ function _readGeneralNames(buffer, block) {
731
945
  }
732
946
  const n = {};
733
947
  for (const block2 of blocks) {
734
- assert3((block2.tag & 128) === 128);
948
+ assert4((block2.tag & 128) === 128);
735
949
  const t2 = block2.tag & 127;
736
950
  const type = _data[t2];
737
951
  if (!type) {
738
- console.log("_readGeneralNames: INVALID TYPE => " + t2 + " 0x" + t2.toString(16));
952
+ console.log(`_readGeneralNames: INVALID TYPE => ${t2} 0x${t2.toString(16)}`);
739
953
  continue;
740
954
  }
741
- if (t2 == 32) {
955
+ if (t2 === 32) {
742
956
  n[type.name] = n[type.name] || [];
743
957
  const blocks2 = readStruct(buffer, block2);
744
958
  const name = readObjectIdentifier(buffer, blocks2[0]).name;
@@ -761,7 +975,7 @@ function _readSubjectAltNames(buffer) {
761
975
  const block_info = readTag(buffer, 0);
762
976
  return _readGeneralNames(buffer, block_info);
763
977
  }
764
- function readKeyUsage(oid, buffer) {
978
+ function readKeyUsage(_oid, buffer) {
765
979
  const block_info = readTag(buffer, 0);
766
980
  let b2 = 0;
767
981
  let b3 = 0;
@@ -791,7 +1005,7 @@ function readKeyUsage(oid, buffer) {
791
1005
  };
792
1006
  }
793
1007
  function readExtKeyUsage(oid, buffer) {
794
- assert3(oid === "2.5.29.37");
1008
+ assert4(oid === "2.5.29.37");
795
1009
  const block_info = readTag(buffer, 0);
796
1010
  const inner_blocks = readStruct(buffer, block_info);
797
1011
  const extKeyUsage = {
@@ -821,7 +1035,7 @@ function _readSubjectPublicKey(buffer) {
821
1035
  function readExtension(buffer, block) {
822
1036
  const inner_blocks = readStruct(buffer, block);
823
1037
  if (inner_blocks.length === 3) {
824
- assert3(inner_blocks[1].tag === 1 /* BOOLEAN */);
1038
+ assert4(inner_blocks[1].tag === 1 /* BOOLEAN */);
825
1039
  inner_blocks[1] = inner_blocks[2];
826
1040
  }
827
1041
  const identifier = readObjectIdentifier(buffer, inner_blocks[0]);
@@ -841,7 +1055,7 @@ function readExtension(buffer, block) {
841
1055
  value = readBasicConstraint2_5_29_19(buf, inner_blocks[1]);
842
1056
  break;
843
1057
  case "certExtension":
844
- value = "basicConstraints ( not implemented yet) " + buf.toString("hex");
1058
+ value = `basicConstraints ( not implemented yet) ${buf.toString("hex")}`;
845
1059
  break;
846
1060
  case "extKeyUsage":
847
1061
  value = readExtKeyUsage(identifier.oid, buf);
@@ -850,7 +1064,7 @@ function readExtension(buffer, block) {
850
1064
  value = readKeyUsage(identifier.oid, buf);
851
1065
  break;
852
1066
  default:
853
- value = "Unknown " + identifier.name + buf.toString("hex");
1067
+ value = `Unknown ${identifier.name}${buf.toString("hex")}`;
854
1068
  }
855
1069
  return {
856
1070
  identifier,
@@ -858,7 +1072,7 @@ function readExtension(buffer, block) {
858
1072
  };
859
1073
  }
860
1074
  function _readExtensions(buffer, block) {
861
- assert3(block.tag === 163);
1075
+ assert4(block.tag === 163);
862
1076
  let inner_blocks = readStruct(buffer, block);
863
1077
  inner_blocks = readStruct(buffer, inner_blocks[0]);
864
1078
  const extensions = inner_blocks.map((block2) => readExtension(buffer, block2));
@@ -897,10 +1111,17 @@ function _readSubjectECCPublicKeyInfo(buffer, block) {
897
1111
  }
898
1112
  function readTbsCertificate(buffer, block) {
899
1113
  const blocks = readStruct(buffer, block);
900
- let version, serialNumber, signature, issuer, validity, subject, subjectFingerPrint, extensions;
1114
+ let _version;
1115
+ let serialNumber;
1116
+ let signature;
1117
+ let issuer;
1118
+ let validity;
1119
+ let subject;
1120
+ let subjectFingerPrint;
1121
+ let extensions;
901
1122
  let subjectPublicKeyInfo;
902
1123
  if (blocks.length === 6) {
903
- version = 1;
1124
+ _version = 1;
904
1125
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[0]));
905
1126
  signature = readAlgorithmIdentifier(buffer, blocks[1]);
906
1127
  issuer = _readName(buffer, blocks[2]);
@@ -914,7 +1135,7 @@ function readTbsCertificate(buffer, block) {
914
1135
  if (!version_block) {
915
1136
  throw new Error("cannot find version block");
916
1137
  }
917
- version = readVersionValue(buffer, version_block) + 1;
1138
+ _version = readVersionValue(buffer, version_block) + 1;
918
1139
  serialNumber = formatBuffer2DigitHexWithColum(readLongIntegerValue(buffer, blocks[1]));
919
1140
  signature = readAlgorithmIdentifier(buffer, blocks[2]);
920
1141
  issuer = _readName(buffer, blocks[3]);
@@ -928,371 +1149,70 @@ function readTbsCertificate(buffer, block) {
928
1149
  subjectPublicKeyInfo = _readSubjectPublicKeyInfo(buffer, blocks[6]);
929
1150
  break;
930
1151
  }
931
- case "ecPublicKey":
932
1152
  default: {
1153
+ assert4(what_type === "ecPublicKey");
933
1154
  subjectPublicKeyInfo = _readSubjectECCPublicKeyInfo(buffer, blocks[6]);
934
1155
  break;
935
1156
  }
936
1157
  }
937
1158
  const extensionBlock = findBlockAtIndex(blocks, 3);
938
1159
  if (!extensionBlock) {
939
- doDebug && console.log("X509 certificate is invalid : cannot find extension block version =" + version_block);
1160
+ doDebug && console.log(`X509 certificate is invalid : cannot find extension block version = ${version_block}`);
940
1161
  extensions = null;
941
1162
  } else {
942
- extensions = _readExtensions(buffer, extensionBlock);
943
- }
944
- }
945
- return {
946
- version,
947
- serialNumber,
948
- signature,
949
- issuer,
950
- validity,
951
- subject,
952
- subjectFingerPrint,
953
- subjectPublicKeyInfo,
954
- extensions
955
- };
956
- }
957
- function exploreCertificate(certificate) {
958
- assert3(Buffer.isBuffer(certificate));
959
- if (!certificate._exploreCertificate_cache) {
960
- const block_info = readTag(certificate, 0);
961
- const blocks = readStruct(certificate, block_info);
962
- certificate._exploreCertificate_cache = {
963
- tbsCertificate: readTbsCertificate(certificate, blocks[0]),
964
- signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
965
- signatureValue: readSignatureValue(certificate, blocks[2])
966
- };
967
- }
968
- return certificate._exploreCertificate_cache;
969
- }
970
- function split_der(certificateChain) {
971
- const certificate_chain = [];
972
- do {
973
- const block_info = readTag(certificateChain, 0);
974
- const length = block_info.position + block_info.length;
975
- const der_certificate = certificateChain.subarray(0, length);
976
- certificate_chain.push(der_certificate);
977
- certificateChain = certificateChain.subarray(length);
978
- } while (certificateChain.length > 0);
979
- return certificate_chain;
980
- }
981
- function combine_der(certificates) {
982
- for (const cert of certificates) {
983
- const b = split_der(cert);
984
- let sum = 0;
985
- b.forEach((block) => {
986
- const block_info = readTag(block, 0);
987
- assert3(block_info.position + block_info.length === block.length);
988
- sum += block.length;
989
- });
990
- assert3(sum === cert.length);
991
- }
992
- return Buffer.concat(certificates);
993
- }
994
-
995
- // source/crypto_utils.ts
996
- import jsrsasign from "jsrsasign";
997
- var { hexy } = pkg_hexy;
998
- var PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
999
- var PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
1000
- function identifyPemType(rawKey) {
1001
- if (Buffer.isBuffer(rawKey)) {
1002
- rawKey = rawKey.toString("utf8");
1003
- }
1004
- const match = PEM_TYPE_REGEX.exec(rawKey);
1005
- return !match ? void 0 : match[2];
1006
- }
1007
- function removeTrailingLF(str) {
1008
- const tmp = str.replace(/(\r|\n)+$/m, "").replace(/\r\n/gm, "\n");
1009
- return tmp;
1010
- }
1011
- function toPem(raw_key, pem) {
1012
- assert4(raw_key, "expecting a key");
1013
- assert4(typeof pem === "string");
1014
- let pemType = identifyPemType(raw_key);
1015
- if (pemType) {
1016
- return Buffer.isBuffer(raw_key) ? removeTrailingLF(raw_key.toString("utf8")) : removeTrailingLF(raw_key);
1017
- } else {
1018
- pemType = pem;
1019
- assert4(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
1020
- let b = raw_key.toString("base64");
1021
- let str = "-----BEGIN " + pemType + "-----\n";
1022
- while (b.length) {
1023
- str += b.substring(0, 64) + "\n";
1024
- b = b.substring(64);
1025
- }
1026
- str += "-----END " + pemType + "-----";
1027
- return str;
1028
- }
1029
- }
1030
- function convertPEMtoDER(raw_key) {
1031
- let match;
1032
- let pemType;
1033
- let base64str;
1034
- const parts = [];
1035
- PEM_REGEX.lastIndex = 0;
1036
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
1037
- pemType = match[2];
1038
- base64str = match[3];
1039
- base64str = base64str.replace(/\r?\n/g, "");
1040
- parts.push(Buffer.from(base64str, "base64"));
1041
- }
1042
- return combine_der(parts);
1043
- }
1044
- function hexDump(buffer, width) {
1045
- if (!buffer) {
1046
- return "<>";
1047
- }
1048
- width = width || 32;
1049
- if (buffer.length > 1024) {
1050
- return hexy(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
1051
- } else {
1052
- return hexy(buffer, { width, format: "twos" });
1053
- }
1054
- }
1055
- function makeMessageChunkSignature(chunk, options) {
1056
- const signer = createSign(options.algorithm);
1057
- signer.update(chunk);
1058
- const signature = signer.sign(options.privateKey.hidden);
1059
- assert4(!options.signatureLength || signature.length === options.signatureLength);
1060
- return signature;
1061
- }
1062
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
1063
- const verify = createVerify(options.algorithm);
1064
- verify.update(blockToVerify);
1065
- return verify.verify(options.publicKey, signature);
1066
- }
1067
- function makeSHA1Thumbprint(buffer) {
1068
- return createHash("sha1").update(buffer).digest();
1069
- }
1070
- var RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
1071
- var RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
1072
- var PaddingAlgorithm = /* @__PURE__ */ ((PaddingAlgorithm2) => {
1073
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
1074
- PaddingAlgorithm2[PaddingAlgorithm2["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
1075
- return PaddingAlgorithm2;
1076
- })(PaddingAlgorithm || {});
1077
- assert4(4 /* RSA_PKCS1_OAEP_PADDING */ === constants.RSA_PKCS1_OAEP_PADDING);
1078
- assert4(1 /* RSA_PKCS1_PADDING */ === constants.RSA_PKCS1_PADDING);
1079
- function publicEncrypt_native(buffer, publicKey, algorithm) {
1080
- if (algorithm === void 0) {
1081
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1082
- }
1083
- return publicEncrypt1(
1084
- {
1085
- key: publicKey,
1086
- padding: algorithm
1087
- },
1088
- buffer
1089
- );
1090
- }
1091
- function privateDecrypt_native(buffer, privateKey, algorithm) {
1092
- if (algorithm === void 0) {
1093
- algorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1094
- }
1095
- try {
1096
- return privateDecrypt1(
1097
- {
1098
- key: privateKey.hidden,
1099
- padding: algorithm
1100
- },
1101
- buffer
1102
- );
1103
- } catch (err) {
1104
- return Buffer.alloc(1);
1105
- }
1106
- }
1107
- var publicEncrypt = publicEncrypt_native;
1108
- var privateDecrypt = privateDecrypt_native;
1109
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
1110
- if (paddingAlgorithm === void 0) {
1111
- paddingAlgorithm = 4 /* RSA_PKCS1_OAEP_PADDING */;
1112
- }
1113
- if (paddingAlgorithm === RSA_PKCS1_PADDING) {
1114
- padding = padding || 11;
1115
- if (padding !== 11) throw new Error("padding should be 11");
1116
- } else if (paddingAlgorithm === RSA_PKCS1_OAEP_PADDING) {
1117
- padding = padding || 42;
1118
- if (padding !== 42) throw new Error("padding should be 42");
1119
- } else {
1120
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1121
- }
1122
- const chunk_size = blockSize - padding;
1123
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
1124
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1125
- for (let i = 0; i < nbBlocks; i++) {
1126
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
1127
- const encrypted_chunk = publicEncrypt(currentBlock, publicKey, paddingAlgorithm);
1128
- if (encrypted_chunk.length !== blockSize) {
1129
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
1130
- }
1131
- encrypted_chunk.copy(outputBuffer, i * blockSize);
1132
- }
1133
- return outputBuffer;
1134
- }
1135
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
1136
- paddingAlgorithm = paddingAlgorithm || RSA_PKCS1_OAEP_PADDING;
1137
- if (paddingAlgorithm !== RSA_PKCS1_PADDING && paddingAlgorithm !== RSA_PKCS1_OAEP_PADDING) {
1138
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
1139
- }
1140
- const nbBlocks = Math.ceil(buffer.length / blockSize);
1141
- const outputBuffer = createFastUninitializedBuffer(nbBlocks * blockSize);
1142
- let total_length = 0;
1143
- for (let i = 0; i < nbBlocks; i++) {
1144
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
1145
- const decrypted_buf = privateDecrypt(currentBlock, privateKey, paddingAlgorithm);
1146
- decrypted_buf.copy(outputBuffer, total_length);
1147
- total_length += decrypted_buf.length;
1148
- }
1149
- return outputBuffer.subarray(0, total_length);
1150
- }
1151
- function coerceCertificatePem(certificate) {
1152
- if (Buffer.isBuffer(certificate)) {
1153
- certificate = toPem(certificate, "CERTIFICATE");
1154
- }
1155
- assert4(typeof certificate === "string");
1156
- return certificate;
1157
- }
1158
- function extractPublicKeyFromCertificateSync(certificate) {
1159
- certificate = coerceCertificatePem(certificate);
1160
- const key = jsrsasign.KEYUTIL.getKey(certificate);
1161
- const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
1162
- assert4(typeof publicKeyAsPem === "string");
1163
- return publicKeyAsPem;
1164
- }
1165
- function extractPublicKeyFromCertificate(certificate, callback) {
1166
- let err1 = null;
1167
- let keyPem;
1168
- try {
1169
- keyPem = extractPublicKeyFromCertificateSync(certificate);
1170
- } catch (err) {
1171
- err1 = err;
1172
- }
1173
- setImmediate(() => {
1174
- callback(err1, keyPem);
1175
- });
1176
- }
1177
-
1178
- // source/explore_private_key.ts
1179
- function f(buffer, b) {
1180
- return buffer.subarray(b.position + 1, b.position + b.length);
1181
- }
1182
- var doDebug2 = !!process.env.DEBUG;
1183
- function explorePrivateKey(privateKey2) {
1184
- const privateKey1 = privateKey2.hidden;
1185
- const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1186
- const block_info = readTag(privateKey, 0);
1187
- const blocks = readStruct(privateKey, block_info);
1188
- if (blocks.length === 9) {
1189
- const version2 = f(privateKey, blocks[0]);
1190
- const modulus2 = f(privateKey, blocks[1]);
1191
- const publicExponent2 = f(privateKey, blocks[2]);
1192
- const privateExponent2 = f(privateKey, blocks[3]);
1193
- const prime12 = f(privateKey, blocks[4]);
1194
- const prime22 = f(privateKey, blocks[5]);
1195
- const exponent12 = f(privateKey, blocks[6]);
1196
- const exponent22 = f(privateKey, blocks[7]);
1197
- return {
1198
- version: version2,
1199
- modulus: modulus2,
1200
- publicExponent: publicExponent2,
1201
- privateExponent: privateExponent2,
1202
- prime1: prime12,
1203
- prime2: prime22,
1204
- exponent1: exponent12,
1205
- exponent2: exponent22
1206
- };
1207
- }
1208
- if (doDebug2) {
1209
- console.log("-------------------- private key:");
1210
- console.log(block_info);
1211
- console.log(
1212
- blocks.map((b2) => ({
1213
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1214
- l: b2.length,
1215
- p: b2.position,
1216
- buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1217
- }))
1218
- );
1219
- }
1220
- const b = blocks[2];
1221
- const bb = privateKey.subarray(b.position, b.position + b.length);
1222
- const block_info1 = readTag(bb, 0);
1223
- const blocks1 = readStruct(bb, block_info1);
1224
- if (doDebug2) {
1225
- console.log(
1226
- blocks1.map((b2) => ({
1227
- tag: TagType[b2.tag] + " 0x" + b2.tag.toString(16),
1228
- l: b2.length,
1229
- p: b2.position,
1230
- buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1231
- }))
1232
- );
1163
+ extensions = _readExtensions(buffer, extensionBlock);
1164
+ }
1233
1165
  }
1234
- const version = f(bb, blocks1[0]);
1235
- const modulus = f(bb, blocks1[1]);
1236
- const publicExponent = f(bb, blocks1[2]);
1237
- const privateExponent = f(bb, blocks1[3]);
1238
- const prime1 = f(bb, blocks1[4]);
1239
- const prime2 = f(bb, blocks1[5]);
1240
- const exponent1 = f(bb, blocks1[6]);
1241
- const exponent2 = f(bb, blocks1[7]);
1242
1166
  return {
1243
- version,
1244
- modulus,
1245
- publicExponent,
1246
- privateExponent,
1247
- prime1,
1248
- prime2,
1249
- exponent1,
1250
- exponent2
1167
+ version: _version,
1168
+ serialNumber,
1169
+ signature,
1170
+ issuer,
1171
+ validity,
1172
+ subject,
1173
+ subjectFingerPrint,
1174
+ subjectPublicKeyInfo,
1175
+ extensions
1251
1176
  };
1252
1177
  }
1253
-
1254
- // source/public_private_match.ts
1255
- function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1256
- const i = exploreCertificate(certificate);
1257
- const j = explorePrivateKey(privateKey);
1258
- const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1259
- const modulus2 = j.modulus;
1260
- if (modulus1.length != modulus2.length) {
1261
- return false;
1178
+ function exploreCertificate(certificate) {
1179
+ assert4(Buffer.isBuffer(certificate));
1180
+ const certificate_priv = certificate;
1181
+ if (!certificate_priv._exploreCertificate_cache) {
1182
+ const block_info = readTag(certificate, 0);
1183
+ const blocks = readStruct(certificate, block_info);
1184
+ certificate_priv._exploreCertificate_cache = {
1185
+ tbsCertificate: readTbsCertificate(certificate, blocks[0]),
1186
+ signatureAlgorithm: readAlgorithmIdentifier(certificate, blocks[1]),
1187
+ signatureValue: readSignatureValue(certificate, blocks[2])
1188
+ };
1262
1189
  }
1263
- return modulus1.toString("hex") === modulus2.toString("hex");
1264
- }
1265
- function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1266
- const initialBuffer = Buffer.from("Lorem Ipsum");
1267
- const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1268
- const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1269
- const finalString = decryptedBuffer.toString("utf-8");
1270
- return initialBuffer.toString("utf-8") === finalString;
1190
+ return certificate_priv._exploreCertificate_cache;
1271
1191
  }
1272
- function certificateMatchesPrivateKey(certificate, privateKey) {
1273
- const e = explorePrivateKey(privateKey);
1274
- const blockSize = e.modulus.length;
1275
- const certificatePEM = toPem(certificate, "CERTIFICATE");
1276
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1192
+ function split_der(certificateChain) {
1193
+ const certificate_chain = [];
1194
+ do {
1195
+ const block_info = readTag(certificateChain, 0);
1196
+ const length = block_info.position + block_info.length;
1197
+ const der_certificate = certificateChain.subarray(0, length);
1198
+ certificate_chain.push(der_certificate);
1199
+ certificateChain = certificateChain.subarray(length);
1200
+ } while (certificateChain.length > 0);
1201
+ return certificate_chain;
1277
1202
  }
1278
-
1279
- // source/common.ts
1280
- import __crypto from "crypto";
1281
- var KeyObjectOrig = __crypto.KeyObject;
1282
- var { createPrivateKey: createPrivateKeyFromNodeJSCrypto } = __crypto;
1283
- function isKeyObject(mayBeKeyObject) {
1284
- if (KeyObjectOrig) {
1285
- return mayBeKeyObject instanceof KeyObjectOrig;
1203
+ function combine_der(certificates) {
1204
+ for (const cert of certificates) {
1205
+ const b = split_der(cert);
1206
+ let sum = 0;
1207
+ b.forEach((block) => {
1208
+ const block_info = readTag(block, 0);
1209
+ assert4(block_info.position + block_info.length === block.length);
1210
+ sum += block.length;
1211
+ });
1212
+ assert4(sum === cert.length);
1286
1213
  }
1287
- return typeof mayBeKeyObject === "object" && typeof mayBeKeyObject.type === "string";
1214
+ return Buffer.concat(certificates);
1288
1215
  }
1289
- var CertificatePurpose = /* @__PURE__ */ ((CertificatePurpose2) => {
1290
- CertificatePurpose2[CertificatePurpose2["NotSpecified"] = 0] = "NotSpecified";
1291
- CertificatePurpose2[CertificatePurpose2["ForCertificateAuthority"] = 1] = "ForCertificateAuthority";
1292
- CertificatePurpose2[CertificatePurpose2["ForApplication"] = 2] = "ForApplication";
1293
- CertificatePurpose2[CertificatePurpose2["ForUserAuthentication"] = 3] = "ForUserAuthentication";
1294
- return CertificatePurpose2;
1295
- })(CertificatePurpose || {});
1296
1216
 
1297
1217
  // source/crypto_utils2.ts
1298
1218
  import assert5 from "assert";
@@ -1374,7 +1294,7 @@ function exploreCertificateInfo(certificate) {
1374
1294
  subject: certInfo.tbsCertificate.subject
1375
1295
  };
1376
1296
  if (!(data.publicKeyLength === 512 || data.publicKeyLength === 384 || data.publicKeyLength === 256 || data.publicKeyLength === 128)) {
1377
- throw new Error("Invalid public key length (expecting 128,256,384 or 512)" + data.publicKeyLength);
1297
+ throw new Error(`Invalid public key length (expecting 128,256,384 or 512): ${data.publicKeyLength}`);
1378
1298
  }
1379
1299
  return data;
1380
1300
  }
@@ -1442,14 +1362,14 @@ function verifyChunkSignature(chunk, options) {
1442
1362
  return verifyMessageChunkSignature(block_to_verify, signature, options);
1443
1363
  }
1444
1364
  function computePaddingFooter(buffer, derivedKeys) {
1445
- assert7(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
1365
+ assert7(Object.hasOwn(derivedKeys, "encryptingBlockSize"));
1446
1366
  const paddingSize = derivedKeys.encryptingBlockSize - (buffer.length + 1) % derivedKeys.encryptingBlockSize;
1447
1367
  const padding = createFastUninitializedBuffer(paddingSize + 1);
1448
1368
  padding.fill(paddingSize);
1449
1369
  return padding;
1450
1370
  }
1451
1371
  function derivedKeys_algorithm(derivedKeys) {
1452
- assert7(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
1372
+ assert7(Object.hasOwn(derivedKeys, "algorithm"));
1453
1373
  const algorithm = derivedKeys.algorithm || "aes-128-cbc";
1454
1374
  assert7(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
1455
1375
  return algorithm;
@@ -1527,7 +1447,7 @@ function _readTbsCertList(buffer, blockInfo) {
1527
1447
  const blocks = readStruct(buffer, blockInfo);
1528
1448
  const hasOptionalVersion = blocks[0].tag === 2 /* INTEGER */;
1529
1449
  if (hasOptionalVersion) {
1530
- const version = readIntegerValue(buffer, blocks[0]);
1450
+ const _version = readIntegerValue(buffer, blocks[0]);
1531
1451
  const signature = readAlgorithmIdentifier(buffer, blocks[1]);
1532
1452
  const issuer = readNameForCrl(buffer, blocks[2]);
1533
1453
  const issuerFingerprint = formatBuffer2DigitHexWithColum(makeSHA1Thumbprint(getBlock(buffer, blocks[2])));
@@ -1546,7 +1466,7 @@ function _readTbsCertList(buffer, blockInfo) {
1546
1466
  });
1547
1467
  }
1548
1468
  }
1549
- const ext0 = findBlockAtIndex(blocks, 0);
1469
+ const _ext0 = findBlockAtIndex(blocks, 0);
1550
1470
  return { issuer, issuerFingerprint, thisUpdate, nextUpdate, signature, revokedCertificates };
1551
1471
  } else {
1552
1472
  const signature = readAlgorithmIdentifier(buffer, blocks[0]);
@@ -1586,10 +1506,21 @@ function _readExtensionRequest(buffer) {
1586
1506
  const extensions = inner_blocks.map((block1) => readExtension(buffer, block1));
1587
1507
  const result = {};
1588
1508
  for (const e of extensions) {
1589
- result[e.identifier.name] = e.value;
1509
+ switch (e.identifier.name) {
1510
+ case "basicConstraints":
1511
+ result.basicConstraints = e.value;
1512
+ break;
1513
+ case "keyUsage":
1514
+ result.keyUsage = e.value;
1515
+ break;
1516
+ case "subjectAltName":
1517
+ result.subjectAltName = e.value;
1518
+ break;
1519
+ default:
1520
+ break;
1521
+ }
1590
1522
  }
1591
- const { basicConstraints, keyUsage, subjectAltName } = result;
1592
- return { basicConstraints, keyUsage, subjectAltName };
1523
+ return result;
1593
1524
  }
1594
1525
  function readCertificationRequestInfo(buffer, block) {
1595
1526
  const blocks = readStruct(buffer, block);
@@ -1617,16 +1548,117 @@ function exploreCertificateSigningRequest(crl) {
1617
1548
  return csrInfo;
1618
1549
  }
1619
1550
 
1551
+ // source/explore_private_key.ts
1552
+ function f(buffer, b) {
1553
+ return buffer.subarray(b.position + 1, b.position + b.length);
1554
+ }
1555
+ var doDebug2 = !!process.env.DEBUG;
1556
+ function explorePrivateKey(privateKey2) {
1557
+ const privateKey1 = privateKey2.hidden;
1558
+ const privateKey = typeof privateKey1 === "string" ? convertPEMtoDER(privateKey1) : privateKey1.export({ format: "der", type: "pkcs1" });
1559
+ const block_info = readTag(privateKey, 0);
1560
+ const blocks = readStruct(privateKey, block_info);
1561
+ if (blocks.length === 9) {
1562
+ const version2 = f(privateKey, blocks[0]);
1563
+ const modulus2 = f(privateKey, blocks[1]);
1564
+ const publicExponent2 = f(privateKey, blocks[2]);
1565
+ const privateExponent2 = f(privateKey, blocks[3]);
1566
+ const prime12 = f(privateKey, blocks[4]);
1567
+ const prime22 = f(privateKey, blocks[5]);
1568
+ const exponent12 = f(privateKey, blocks[6]);
1569
+ const exponent22 = f(privateKey, blocks[7]);
1570
+ return {
1571
+ version: version2,
1572
+ modulus: modulus2,
1573
+ publicExponent: publicExponent2,
1574
+ privateExponent: privateExponent2,
1575
+ prime1: prime12,
1576
+ prime2: prime22,
1577
+ exponent1: exponent12,
1578
+ exponent2: exponent22
1579
+ };
1580
+ }
1581
+ if (doDebug2) {
1582
+ console.log("-------------------- private key:");
1583
+ console.log(block_info);
1584
+ console.log(
1585
+ blocks.map((b2) => ({
1586
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1587
+ l: b2.length,
1588
+ p: b2.position,
1589
+ buff: privateKey.subarray(b2.position, b2.position + b2.length).toString("hex")
1590
+ }))
1591
+ );
1592
+ }
1593
+ const b = blocks[2];
1594
+ const bb = privateKey.subarray(b.position, b.position + b.length);
1595
+ const block_info1 = readTag(bb, 0);
1596
+ const blocks1 = readStruct(bb, block_info1);
1597
+ if (doDebug2) {
1598
+ console.log(
1599
+ blocks1.map((b2) => ({
1600
+ tag: `${TagType[b2.tag]} 0x${b2.tag.toString(16)}`,
1601
+ l: b2.length,
1602
+ p: b2.position,
1603
+ buff: bb.subarray(b2.position, b2.position + b2.length).toString("hex")
1604
+ }))
1605
+ );
1606
+ }
1607
+ const version = f(bb, blocks1[0]);
1608
+ const modulus = f(bb, blocks1[1]);
1609
+ const publicExponent = f(bb, blocks1[2]);
1610
+ const privateExponent = f(bb, blocks1[3]);
1611
+ const prime1 = f(bb, blocks1[4]);
1612
+ const prime2 = f(bb, blocks1[5]);
1613
+ const exponent1 = f(bb, blocks1[6]);
1614
+ const exponent2 = f(bb, blocks1[7]);
1615
+ return {
1616
+ version,
1617
+ modulus,
1618
+ publicExponent,
1619
+ privateExponent,
1620
+ prime1,
1621
+ prime2,
1622
+ exponent1,
1623
+ exponent2
1624
+ };
1625
+ }
1626
+
1620
1627
  // source/make_private_key_from_pem.ts
1621
1628
  function makePrivateKeyFromPem(privateKeyInPem) {
1622
1629
  return { hidden: privateKeyInPem };
1623
1630
  }
1624
1631
 
1625
1632
  // source/make_private_key_thumbprint.ts
1626
- function makePrivateKeyThumbPrint(privateKey) {
1633
+ function makePrivateKeyThumbPrint(_privateKey) {
1627
1634
  return Buffer.alloc(0);
1628
1635
  }
1629
1636
 
1637
+ // source/public_private_match.ts
1638
+ function publicKeyAndPrivateKeyMatches(certificate, privateKey) {
1639
+ const i = exploreCertificate(certificate);
1640
+ const j = explorePrivateKey(privateKey);
1641
+ const modulus1 = i.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus;
1642
+ const modulus2 = j.modulus;
1643
+ if (modulus1.length !== modulus2.length) {
1644
+ return false;
1645
+ }
1646
+ return modulus1.toString("hex") === modulus2.toString("hex");
1647
+ }
1648
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey, blockSize) {
1649
+ const initialBuffer = Buffer.from("Lorem Ipsum");
1650
+ const encryptedBuffer = publicEncrypt_long(initialBuffer, certificate, blockSize);
1651
+ const decryptedBuffer = privateDecrypt_long(encryptedBuffer, privateKey, blockSize);
1652
+ const finalString = decryptedBuffer.toString("utf-8");
1653
+ return initialBuffer.toString("utf-8") === finalString;
1654
+ }
1655
+ function certificateMatchesPrivateKey(certificate, privateKey) {
1656
+ const e = explorePrivateKey(privateKey);
1657
+ const blockSize = e.modulus.length;
1658
+ const certificatePEM = toPem(certificate, "CERTIFICATE");
1659
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKey, blockSize);
1660
+ }
1661
+
1630
1662
  // source/subject.ts
1631
1663
  var _keys = {
1632
1664
  C: "country",
@@ -1669,11 +1701,11 @@ var Subject = class _Subject {
1669
1701
  }
1670
1702
  const s = element.split("=");
1671
1703
  if (s.length !== 2) {
1672
- throw new Error("invalid format for " + element);
1704
+ throw new Error(`invalid format for ${element}`);
1673
1705
  }
1674
1706
  const longName = _keys[s[0]];
1675
1707
  if (!longName) {
1676
- throw new Error("Invalid field found in subject name " + s[0]);
1708
+ throw new Error(`Invalid field found in subject name ${s[0]}`);
1677
1709
  }
1678
1710
  const value = s[1];
1679
1711
  options[longName] = unquote(Buffer.from(value, "ascii").toString("utf8"));
@@ -1683,25 +1715,25 @@ var Subject = class _Subject {
1683
1715
  toStringInternal(sep) {
1684
1716
  const tmp = [];
1685
1717
  if (this.country) {
1686
- tmp.push("C=" + enquoteIfNecessary(this.country));
1718
+ tmp.push(`C=${enquoteIfNecessary(this.country)}`);
1687
1719
  }
1688
1720
  if (this.state) {
1689
- tmp.push("ST=" + enquoteIfNecessary(this.state));
1721
+ tmp.push(`ST=${enquoteIfNecessary(this.state)}`);
1690
1722
  }
1691
1723
  if (this.locality) {
1692
- tmp.push("L=" + enquoteIfNecessary(this.locality));
1724
+ tmp.push(`L=${enquoteIfNecessary(this.locality)}`);
1693
1725
  }
1694
1726
  if (this.organization) {
1695
- tmp.push("O=" + enquoteIfNecessary(this.organization));
1727
+ tmp.push(`O=${enquoteIfNecessary(this.organization)}`);
1696
1728
  }
1697
1729
  if (this.organizationalUnit) {
1698
- tmp.push("OU=" + enquoteIfNecessary(this.organizationalUnit));
1730
+ tmp.push(`OU=${enquoteIfNecessary(this.organizationalUnit)}`);
1699
1731
  }
1700
1732
  if (this.commonName) {
1701
- tmp.push("CN=" + enquoteIfNecessary(this.commonName));
1733
+ tmp.push(`CN=${enquoteIfNecessary(this.commonName)}`);
1702
1734
  }
1703
1735
  if (this.domainComponent) {
1704
- tmp.push("DC=" + enquoteIfNecessary(this.domainComponent));
1736
+ tmp.push(`DC=${enquoteIfNecessary(this.domainComponent)}`);
1705
1737
  }
1706
1738
  return tmp.join(sep);
1707
1739
  }
@@ -1710,7 +1742,7 @@ var Subject = class _Subject {
1710
1742
  }
1711
1743
  toString() {
1712
1744
  const t2 = this.toStringForOPCUA();
1713
- return t2 ? "/" + t2 : t2;
1745
+ return t2 ? `/${t2}` : t2;
1714
1746
  }
1715
1747
  };
1716
1748
 
@@ -1740,8 +1772,8 @@ async function verifyCertificateChain(certificateChain) {
1740
1772
  const cert = certificateChain[index - 1];
1741
1773
  const certParent = certificateChain[index];
1742
1774
  const certParentInfo = exploreCertificate(certParent);
1743
- const keyUsage = certParentInfo.tbsCertificate.extensions.keyUsage;
1744
- if (!keyUsage.keyCertSign) {
1775
+ const keyUsage = certParentInfo.tbsCertificate.extensions?.keyUsage;
1776
+ if (!keyUsage || !keyUsage.keyCertSign) {
1745
1777
  return {
1746
1778
  status: "BadCertificateIssuerUseNotAllowed",
1747
1779
  reason: "One of the certificate in the chain has not keyUsage set for Certificate Signing"
@@ -1781,9 +1813,9 @@ async function verifyCertificateChain(certificateChain) {
1781
1813
  }
1782
1814
 
1783
1815
  // source/x509/_crypto.ts
1784
- import * as x509 from "@peculiar/x509";
1785
- import { Crypto as PeculiarWebCrypto } from "@peculiar/webcrypto";
1786
1816
  import nativeCrypto from "crypto";
1817
+ import { Crypto as PeculiarWebCrypto } from "@peculiar/webcrypto";
1818
+ import * as x509 from "@peculiar/x509";
1787
1819
  import * as x5092 from "@peculiar/x509";
1788
1820
  var doDebug3 = false;
1789
1821
  var _crypto;
@@ -1803,7 +1835,7 @@ if (typeof window === "undefined") {
1803
1835
  x509.cryptoProvider.set(crypto);
1804
1836
  }
1805
1837
  function getCrypto() {
1806
- return _crypto || crypto || __require("crypto");
1838
+ return _crypto || crypto || nativeCrypto;
1807
1839
  }
1808
1840
 
1809
1841
  // source/x509/create_key_pair.ts
@@ -1829,7 +1861,7 @@ async function privateKeyToPEM(privateKey) {
1829
1861
  }
1830
1862
  async function derToPrivateKey(privDer) {
1831
1863
  const crypto3 = getCrypto();
1832
- return await crypto3.subtle.importKey(
1864
+ const importedKey = await crypto3.subtle.importKey(
1833
1865
  "pkcs8",
1834
1866
  privDer,
1835
1867
  {
@@ -1848,6 +1880,7 @@ async function derToPrivateKey(privDer) {
1848
1880
  // "deriveBits"
1849
1881
  ]
1850
1882
  );
1883
+ return importedKey;
1851
1884
  }
1852
1885
  async function pemToPrivateKey(pem) {
1853
1886
  const privDer = x5092.PemConverter.decode(pem);
@@ -1865,24 +1898,46 @@ function coercePEMorDerToPrivateKey(privateKeyInDerOrPem) {
1865
1898
  throw new Error("not implemented");
1866
1899
  }
1867
1900
  async function _coercePrivateKey(privateKey) {
1868
- const KeyObject4 = crypto2.KeyObject;
1901
+ const KeyObject = crypto2.KeyObject;
1869
1902
  if (Buffer.isBuffer(privateKey)) {
1870
1903
  const privateKey1 = await derToPrivateKey(privateKey);
1871
- return KeyObject4.from(privateKey1);
1904
+ return KeyObject.from(privateKey1);
1872
1905
  } else if (typeof privateKey === "string") {
1873
1906
  try {
1874
1907
  const privateKey1 = await pemToPrivateKey(privateKey);
1875
- return KeyObject4.from(privateKey1);
1908
+ return KeyObject.from(privateKey1);
1876
1909
  } catch (err) {
1877
1910
  doDebug4 && console.log(privateKey);
1878
1911
  throw err;
1879
1912
  }
1880
- } else if (privateKey instanceof KeyObject4) {
1913
+ } else if (isKeyObject(privateKey)) {
1881
1914
  return privateKey;
1882
1915
  }
1883
1916
  throw new Error("Invalid privateKey");
1884
1917
  }
1885
1918
 
1919
+ // source/x509/_build_public_key.ts
1920
+ async function buildPublicKey(privateKey) {
1921
+ const crypto3 = getCrypto();
1922
+ const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
1923
+ delete jwk.d;
1924
+ delete jwk.dp;
1925
+ delete jwk.dq;
1926
+ delete jwk.q;
1927
+ delete jwk.qi;
1928
+ jwk.key_ops = [
1929
+ "encrypt",
1930
+ "sign"
1931
+ // "wrapKey"
1932
+ ];
1933
+ const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
1934
+ // "encrypt",
1935
+ // "sign",
1936
+ // "wrapKey",
1937
+ ]);
1938
+ return publicKey;
1939
+ }
1940
+
1886
1941
  // source/x509/_get_attributes.ts
1887
1942
  var keyUsageApplication = x5092.KeyUsageFlags.keyEncipherment | x5092.KeyUsageFlags.nonRepudiation | x5092.KeyUsageFlags.dataEncipherment | x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.digitalSignature;
1888
1943
  var keyUsageCA = x5092.KeyUsageFlags.keyCertSign | x5092.KeyUsageFlags.cRLSign;
@@ -1891,19 +1946,19 @@ function getAttributes(purpose) {
1891
1946
  let keyUsageExtension = [];
1892
1947
  let usages;
1893
1948
  let nsComment;
1894
- let extension;
1949
+ let _extension;
1895
1950
  switch (purpose) {
1896
1951
  case 1 /* ForCertificateAuthority */:
1897
- extension = "v3_ca";
1952
+ _extension = "v3_ca";
1898
1953
  basicConstraints = new x5092.BasicConstraintsExtension(true, void 0, false);
1899
1954
  usages = keyUsageCA;
1900
1955
  keyUsageExtension = [];
1901
1956
  nsComment = "Self-signed certificate for CA generated by Node-OPCUA Certificate utility V2";
1902
1957
  break;
1903
- case 2 /* ForApplication */:
1904
- case 3 /* ForUserAuthentication */:
1958
+ // case CertificatePurpose.ForApplication:
1959
+ // case CertificatePurpose.ForUserAuthentication:
1905
1960
  default:
1906
- extension = "v3_selfsigned";
1961
+ _extension = "v3_selfsigned";
1907
1962
  basicConstraints = new x5092.BasicConstraintsExtension(false, void 0, true);
1908
1963
  usages = keyUsageApplication;
1909
1964
  keyUsageExtension = [x5092.ExtendedKeyUsage.serverAuth, x5092.ExtendedKeyUsage.clientAuth];
@@ -1913,28 +1968,6 @@ function getAttributes(purpose) {
1913
1968
  return { nsComment, basicConstraints, keyUsageExtension, usages };
1914
1969
  }
1915
1970
 
1916
- // source/x509/_build_public_key.ts
1917
- async function buildPublicKey(privateKey) {
1918
- const crypto3 = getCrypto();
1919
- const jwk = await crypto3.subtle.exportKey("jwk", privateKey);
1920
- delete jwk.d;
1921
- delete jwk.dp;
1922
- delete jwk.dq;
1923
- delete jwk.q;
1924
- delete jwk.qi;
1925
- jwk.key_ops = [
1926
- "encrypt",
1927
- "sign"
1928
- // "wrapKey"
1929
- ];
1930
- const publicKey = await crypto3.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, true, [
1931
- // "encrypt",
1932
- // "sign",
1933
- // "wrapKey",
1934
- ]);
1935
- return publicKey;
1936
- }
1937
-
1938
1971
  // source/x509/create_certificate_signing_request.ts
1939
1972
  async function createCertificateSigningRequest({
1940
1973
  privateKey,
@@ -1958,9 +1991,15 @@ async function createCertificateSigningRequest({
1958
1991
  publicKey
1959
1992
  };
1960
1993
  const alternativeNameExtensions = [];
1961
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
1962
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
1963
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
1994
+ for (const d of dns ?? []) {
1995
+ alternativeNameExtensions.push({ type: "dns", value: d });
1996
+ }
1997
+ for (const d of ip ?? []) {
1998
+ alternativeNameExtensions.push({ type: "ip", value: d });
1999
+ }
2000
+ if (applicationUri) {
2001
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
2002
+ }
1964
2003
  const { basicConstraints, usages } = getAttributes(purpose);
1965
2004
  const s = new Subject(subject || "");
1966
2005
  const s1 = s.toStringInternal(", ");
@@ -2113,7 +2152,7 @@ var BufferSourceConverter = class _BufferSourceConverter {
2113
2152
  }
2114
2153
  };
2115
2154
  var STRING_TYPE = "string";
2116
- var HEX_REGEX = /^[0-9a-f]+$/i;
2155
+ var HEX_REGEX = /^[0-9a-f\s]+$/i;
2117
2156
  var BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2118
2157
  var BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
2119
2158
  var Utf8Converter = class {
@@ -2561,19 +2600,19 @@ var BIT_STRING_NAME = "BIT STRING";
2561
2600
  function HexBlock(BaseClass) {
2562
2601
  var _a2;
2563
2602
  return _a2 = class Some extends BaseClass {
2564
- constructor(...args) {
2565
- var _a3;
2566
- super(...args);
2567
- const params = args[0] || {};
2568
- this.isHexOnly = (_a3 = params.isHexOnly) !== null && _a3 !== void 0 ? _a3 : false;
2569
- this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2570
- }
2571
2603
  get valueHex() {
2572
2604
  return this.valueHexView.slice().buffer;
2573
2605
  }
2574
2606
  set valueHex(value) {
2575
2607
  this.valueHexView = new Uint8Array(value);
2576
2608
  }
2609
+ constructor(...args) {
2610
+ var _b;
2611
+ super(...args);
2612
+ const params = args[0] || {};
2613
+ this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false;
2614
+ this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
2615
+ }
2577
2616
  fromBER(inputBuffer, inputOffset, inputLength) {
2578
2617
  const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
2579
2618
  if (!checkBufferParams(this, view, inputOffset, inputLength)) {
@@ -2608,12 +2647,6 @@ function HexBlock(BaseClass) {
2608
2647
  }, _a2.NAME = "hexBlock", _a2;
2609
2648
  }
2610
2649
  var LocalBaseBlock = class {
2611
- constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2612
- this.blockLength = blockLength;
2613
- this.error = error;
2614
- this.warnings = warnings;
2615
- this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2616
- }
2617
2650
  static blockName() {
2618
2651
  return this.NAME;
2619
2652
  }
@@ -2623,6 +2656,12 @@ var LocalBaseBlock = class {
2623
2656
  set valueBeforeDecode(value) {
2624
2657
  this.valueBeforeDecodeView = new Uint8Array(value);
2625
2658
  }
2659
+ constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
2660
+ this.blockLength = blockLength;
2661
+ this.error = error;
2662
+ this.warnings = warnings;
2663
+ this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
2664
+ }
2626
2665
  toJSON() {
2627
2666
  return {
2628
2667
  blockName: this.constructor.NAME,
@@ -2635,10 +2674,10 @@ var LocalBaseBlock = class {
2635
2674
  };
2636
2675
  LocalBaseBlock.NAME = "baseBlock";
2637
2676
  var ValueBlock = class extends LocalBaseBlock {
2638
- fromBER(inputBuffer, inputOffset, inputLength) {
2677
+ fromBER(_inputBuffer, _inputOffset, _inputLength) {
2639
2678
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2640
2679
  }
2641
- toBER(sizeOnly, writer) {
2680
+ toBER(_sizeOnly, _writer) {
2642
2681
  throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
2643
2682
  }
2644
2683
  };
@@ -2979,7 +3018,9 @@ var BaseBlock = class extends LocalBaseBlock {
2979
3018
  return Convert.ToHex(this.toBER());
2980
3019
  }
2981
3020
  onAsciiEncoding() {
2982
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;
3021
+ const name = this.constructor.NAME;
3022
+ const value = Convert.ToHex(this.valueBlock.valueBeforeDecodeView);
3023
+ return `${name} : ${value}`;
2983
3024
  }
2984
3025
  isEqual(other) {
2985
3026
  if (this === other) {
@@ -2995,6 +3036,7 @@ var BaseBlock = class extends LocalBaseBlock {
2995
3036
  };
2996
3037
  BaseBlock.NAME = "BaseBlock";
2997
3038
  function prepareIndefiniteForm(baseBlock) {
3039
+ var _a2;
2998
3040
  if (baseBlock instanceof typeStore.Constructed) {
2999
3041
  for (const value of baseBlock.valueBlock.value) {
3000
3042
  if (prepareIndefiniteForm(value)) {
@@ -3002,21 +3044,21 @@ function prepareIndefiniteForm(baseBlock) {
3002
3044
  }
3003
3045
  }
3004
3046
  }
3005
- return !!baseBlock.lenBlock.isIndefiniteForm;
3047
+ return !!((_a2 = baseBlock.lenBlock) === null || _a2 === void 0 ? void 0 : _a2.isIndefiniteForm);
3006
3048
  }
3007
3049
  var BaseStringBlock = class extends BaseBlock {
3008
- constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3009
- super(parameters, stringValueBlockType);
3010
- if (value) {
3011
- this.fromString(value);
3012
- }
3013
- }
3014
3050
  getValue() {
3015
3051
  return this.valueBlock.value;
3016
3052
  }
3017
3053
  setValue(value) {
3018
3054
  this.valueBlock.value = value;
3019
3055
  }
3056
+ constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
3057
+ super(parameters, stringValueBlockType);
3058
+ if (value) {
3059
+ this.fromString(value);
3060
+ }
3061
+ }
3020
3062
  fromBER(inputBuffer, inputOffset, inputLength) {
3021
3063
  const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
3022
3064
  if (resultOffset === -1) {
@@ -3375,10 +3417,10 @@ _a$v = Constructed;
3375
3417
  })();
3376
3418
  Constructed.NAME = "CONSTRUCTED";
3377
3419
  var LocalEndOfContentValueBlock = class extends ValueBlock {
3378
- fromBER(inputBuffer, inputOffset, inputLength) {
3420
+ fromBER(inputBuffer, inputOffset, _inputLength) {
3379
3421
  return inputOffset;
3380
3422
  }
3381
- toBER(sizeOnly) {
3423
+ toBER(_sizeOnly) {
3382
3424
  return EMPTY_BUFFER;
3383
3425
  }
3384
3426
  };
@@ -3439,17 +3481,6 @@ _a$t = Null;
3439
3481
  })();
3440
3482
  Null.NAME = "NULL";
3441
3483
  var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3442
- constructor({ value, ...parameters } = {}) {
3443
- super(parameters);
3444
- if (parameters.valueHex) {
3445
- this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3446
- } else {
3447
- this.valueHexView = new Uint8Array(1);
3448
- }
3449
- if (value) {
3450
- this.value = value;
3451
- }
3452
- }
3453
3484
  get value() {
3454
3485
  for (const octet of this.valueHexView) {
3455
3486
  if (octet > 0) {
@@ -3461,6 +3492,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3461
3492
  set value(value) {
3462
3493
  this.valueHexView[0] = value ? 255 : 0;
3463
3494
  }
3495
+ constructor({ value, ...parameters } = {}) {
3496
+ super(parameters);
3497
+ if (parameters.valueHex) {
3498
+ this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
3499
+ } else {
3500
+ this.valueHexView = new Uint8Array(1);
3501
+ }
3502
+ if (value) {
3503
+ this.value = value;
3504
+ }
3505
+ }
3464
3506
  fromBER(inputBuffer, inputOffset, inputLength) {
3465
3507
  const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
3466
3508
  if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
@@ -3487,17 +3529,17 @@ var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
3487
3529
  LocalBooleanValueBlock.NAME = "BooleanValueBlock";
3488
3530
  var _a$s;
3489
3531
  var Boolean = class extends BaseBlock {
3490
- constructor(parameters = {}) {
3491
- super(parameters, LocalBooleanValueBlock);
3492
- this.idBlock.tagClass = 1;
3493
- this.idBlock.tagNumber = 1;
3494
- }
3495
3532
  getValue() {
3496
3533
  return this.valueBlock.value;
3497
3534
  }
3498
3535
  setValue(value) {
3499
3536
  this.valueBlock.value = value;
3500
3537
  }
3538
+ constructor(parameters = {}) {
3539
+ super(parameters, LocalBooleanValueBlock);
3540
+ this.idBlock.tagClass = 1;
3541
+ this.idBlock.tagNumber = 1;
3542
+ }
3501
3543
  onAsciiEncoding() {
3502
3544
  return `${this.constructor.NAME} : ${this.getValue}`;
3503
3545
  }
@@ -3555,7 +3597,7 @@ var LocalOctetStringValueBlock = class extends HexBlock(LocalConstructedValueBlo
3555
3597
  };
3556
3598
  LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
3557
3599
  var _a$r;
3558
- var OctetString = class _OctetString extends BaseBlock {
3600
+ var OctetString = class extends BaseBlock {
3559
3601
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
3560
3602
  var _b, _c;
3561
3603
  (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length);
@@ -3593,7 +3635,7 @@ var OctetString = class _OctetString extends BaseBlock {
3593
3635
  this.valueBlock.value = [asn.result];
3594
3636
  }
3595
3637
  }
3596
- } catch (e) {
3638
+ } catch {
3597
3639
  }
3598
3640
  }
3599
3641
  return super.fromBER(inputBuffer, inputOffset, inputLength);
@@ -3602,7 +3644,9 @@ var OctetString = class _OctetString extends BaseBlock {
3602
3644
  if (this.valueBlock.isConstructed || this.valueBlock.value && this.valueBlock.value.length) {
3603
3645
  return Constructed.prototype.onAsciiEncoding.call(this);
3604
3646
  }
3605
- return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueHexView)}`;
3647
+ const name = this.constructor.NAME;
3648
+ const value = Convert.ToHex(this.valueBlock.valueHexView);
3649
+ return `${name} : ${value}`;
3606
3650
  }
3607
3651
  getValue() {
3608
3652
  if (!this.idBlock.isConstructed) {
@@ -3610,7 +3654,7 @@ var OctetString = class _OctetString extends BaseBlock {
3610
3654
  }
3611
3655
  const array = [];
3612
3656
  for (const content of this.valueBlock.value) {
3613
- if (content instanceof _OctetString) {
3657
+ if (content instanceof _a$r) {
3614
3658
  array.push(content.valueBlock.valueHexView);
3615
3659
  }
3616
3660
  }
@@ -3680,7 +3724,7 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3680
3724
  this.value = [asn.result];
3681
3725
  }
3682
3726
  }
3683
- } catch (e) {
3727
+ } catch {
3684
3728
  }
3685
3729
  }
3686
3730
  this.valueHexView = intBuffer.subarray(1);
@@ -3695,7 +3739,9 @@ var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock
3695
3739
  return new ArrayBuffer(this.valueHexView.byteLength + 1);
3696
3740
  }
3697
3741
  if (!this.valueHexView.byteLength) {
3698
- return EMPTY_BUFFER;
3742
+ const empty = new Uint8Array(1);
3743
+ empty[0] = 0;
3744
+ return empty.buffer;
3699
3745
  }
3700
3746
  const retView = new Uint8Array(this.valueHexView.length + 1);
3701
3747
  retView[0] = this.unusedBits;
@@ -3745,7 +3791,9 @@ var BitString = class extends BaseBlock {
3745
3791
  bits.push(byte.toString(2).padStart(8, "0"));
3746
3792
  }
3747
3793
  const bitsStr = bits.join("");
3748
- return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;
3794
+ const name = this.constructor.NAME;
3795
+ const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits);
3796
+ return `${name} : ${value}`;
3749
3797
  }
3750
3798
  }
3751
3799
  };
@@ -3842,16 +3890,6 @@ function viewSub(first, second) {
3842
3890
  return firstViewCopy.slice();
3843
3891
  }
3844
3892
  var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3845
- constructor({ value, ...parameters } = {}) {
3846
- super(parameters);
3847
- this._valueDec = 0;
3848
- if (parameters.valueHex) {
3849
- this.setValueHex();
3850
- }
3851
- if (value !== void 0) {
3852
- this.valueDec = value;
3853
- }
3854
- }
3855
3893
  setValueHex() {
3856
3894
  if (this.valueHexView.length >= 4) {
3857
3895
  this.warnings.push("Too big Integer for decoding, hex only");
@@ -3864,6 +3902,16 @@ var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
3864
3902
  }
3865
3903
  }
3866
3904
  }
3905
+ constructor({ value, ...parameters } = {}) {
3906
+ super(parameters);
3907
+ this._valueDec = 0;
3908
+ if (parameters.valueHex) {
3909
+ this.setValueHex();
3910
+ }
3911
+ if (value !== void 0) {
3912
+ this.valueDec = value;
3913
+ }
3914
+ }
3867
3915
  set valueDec(v) {
3868
3916
  this._valueDec = v;
3869
3917
  this.isHexOnly = false;
@@ -3976,7 +4024,7 @@ LocalIntegerValueBlock.NAME = "IntegerValueBlock";
3976
4024
  });
3977
4025
  })();
3978
4026
  var _a$o;
3979
- var Integer = class _Integer extends BaseBlock {
4027
+ var Integer = class extends BaseBlock {
3980
4028
  constructor(parameters = {}) {
3981
4029
  super(parameters, LocalIntegerValueBlock);
3982
4030
  this.idBlock.tagClass = 1;
@@ -4006,18 +4054,16 @@ var Integer = class _Integer extends BaseBlock {
4006
4054
  }
4007
4055
  writer.write(view);
4008
4056
  }
4009
- const res = new _Integer({
4010
- valueHex: writer.final()
4011
- });
4057
+ const res = new _a$o({ valueHex: writer.final() });
4012
4058
  return res;
4013
4059
  }
4014
4060
  convertToDER() {
4015
- const integer = new _Integer({ valueHex: this.valueBlock.valueHexView });
4061
+ const integer = new _a$o({ valueHex: this.valueBlock.valueHexView });
4016
4062
  integer.valueBlock.toDER();
4017
4063
  return integer;
4018
4064
  }
4019
4065
  convertFromDER() {
4020
- return new _Integer({
4066
+ return new _a$o({
4021
4067
  valueHex: this.valueBlock.valueHexView[0] === 0 ? this.valueBlock.valueHexView.subarray(1) : this.valueBlock.valueHexView
4022
4068
  });
4023
4069
  }
@@ -4280,17 +4326,17 @@ var LocalObjectIdentifierValueBlock = class extends ValueBlock {
4280
4326
  LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
4281
4327
  var _a$m;
4282
4328
  var ObjectIdentifier = class extends BaseBlock {
4283
- constructor(parameters = {}) {
4284
- super(parameters, LocalObjectIdentifierValueBlock);
4285
- this.idBlock.tagClass = 1;
4286
- this.idBlock.tagNumber = 6;
4287
- }
4288
4329
  getValue() {
4289
4330
  return this.valueBlock.toString();
4290
4331
  }
4291
4332
  setValue(value) {
4292
4333
  this.valueBlock.fromString(value);
4293
4334
  }
4335
+ constructor(parameters = {}) {
4336
+ super(parameters, LocalObjectIdentifierValueBlock);
4337
+ this.idBlock.tagClass = 1;
4338
+ this.idBlock.tagNumber = 6;
4339
+ }
4294
4340
  onAsciiEncoding() {
4295
4341
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4296
4342
  }
@@ -4410,7 +4456,7 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4410
4456
  }
4411
4457
  return resultOffset;
4412
4458
  }
4413
- toBER(sizeOnly, writer) {
4459
+ toBER(sizeOnly, _writer) {
4414
4460
  const retBuffers = [];
4415
4461
  for (let i = 0; i < this.value.length; i++) {
4416
4462
  const valueBuf = this.value[i].toBER(sizeOnly);
@@ -4472,17 +4518,17 @@ var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
4472
4518
  LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
4473
4519
  var _a$l;
4474
4520
  var RelativeObjectIdentifier = class extends BaseBlock {
4475
- constructor(parameters = {}) {
4476
- super(parameters, LocalRelativeObjectIdentifierValueBlock);
4477
- this.idBlock.tagClass = 1;
4478
- this.idBlock.tagNumber = 13;
4479
- }
4480
4521
  getValue() {
4481
4522
  return this.valueBlock.toString();
4482
4523
  }
4483
4524
  setValue(value) {
4484
4525
  this.valueBlock.fromString(value);
4485
4526
  }
4527
+ constructor(parameters = {}) {
4528
+ super(parameters, LocalRelativeObjectIdentifierValueBlock);
4529
+ this.idBlock.tagClass = 1;
4530
+ this.idBlock.tagNumber = 13;
4531
+ }
4486
4532
  onAsciiEncoding() {
4487
4533
  return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
4488
4534
  }
@@ -4879,7 +4925,8 @@ var GeneralizedTime = class extends UTCTime {
4879
4925
  this.millisecond = inputDate.getUTCMilliseconds();
4880
4926
  }
4881
4927
  toDate() {
4882
- return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond));
4928
+ const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond);
4929
+ return new Date(utcDate);
4883
4930
  }
4884
4931
  fromString(inputString) {
4885
4932
  let isUTC = false;
@@ -5128,28 +5175,28 @@ var Repeated = class extends Any {
5128
5175
  }
5129
5176
  };
5130
5177
  var RawData = class {
5131
- constructor({ data = EMPTY_VIEW } = {}) {
5132
- this.dataView = BufferSourceConverter.toUint8Array(data);
5133
- }
5134
5178
  get data() {
5135
5179
  return this.dataView.slice().buffer;
5136
5180
  }
5137
5181
  set data(value) {
5138
5182
  this.dataView = BufferSourceConverter.toUint8Array(value);
5139
5183
  }
5184
+ constructor({ data = EMPTY_VIEW } = {}) {
5185
+ this.dataView = BufferSourceConverter.toUint8Array(data);
5186
+ }
5140
5187
  fromBER(inputBuffer, inputOffset, inputLength) {
5141
5188
  const endLength = inputOffset + inputLength;
5142
5189
  this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
5143
5190
  return endLength;
5144
5191
  }
5145
- toBER(sizeOnly) {
5192
+ toBER(_sizeOnly) {
5146
5193
  return this.dataView.slice().buffer;
5147
5194
  }
5148
5195
  };
5149
5196
  function compareSchema(root, inputData, inputSchema) {
5150
5197
  if (inputSchema instanceof Choice) {
5151
- for (let j = 0; j < inputSchema.value.length; j++) {
5152
- const result = compareSchema(root, inputData, inputSchema.value[j]);
5198
+ for (const element of inputSchema.value) {
5199
+ const result = compareSchema(root, inputData, element);
5153
5200
  if (result.verified) {
5154
5201
  return {
5155
5202
  verified: true,
@@ -5160,9 +5207,7 @@ function compareSchema(root, inputData, inputSchema) {
5160
5207
  {
5161
5208
  const _result = {
5162
5209
  verified: false,
5163
- result: {
5164
- error: "Wrong values for Choice type"
5165
- }
5210
+ result: { error: "Wrong values for Choice type" }
5166
5211
  };
5167
5212
  if (inputSchema.hasOwnProperty(NAME))
5168
5213
  _result.name = inputSchema.name;
@@ -5308,9 +5353,7 @@ function compareSchema(root, inputData, inputSchema) {
5308
5353
  let admission = 0;
5309
5354
  let result = {
5310
5355
  verified: false,
5311
- result: {
5312
- error: "Unknown error"
5313
- }
5356
+ result: { error: "Unknown error" }
5314
5357
  };
5315
5358
  let maxLength = inputSchema.valueBlock.value.length;
5316
5359
  if (maxLength > 0) {
@@ -5687,10 +5730,7 @@ var AsnSchemaStorage = class {
5687
5730
  }
5688
5731
  }
5689
5732
  createDefault(target) {
5690
- const schema = {
5691
- type: AsnTypeTypes.Sequence,
5692
- items: {}
5693
- };
5733
+ const schema = { type: AsnTypeTypes.Sequence, items: {} };
5694
5734
  const parentSchema = this.findParentSchema(target);
5695
5735
  if (parentSchema) {
5696
5736
  Object.assign(schema, parentSchema);
@@ -5732,26 +5772,14 @@ var AsnSchemaStorage = class {
5732
5772
  const Container = item.repeated === "set" ? Set : Sequence;
5733
5773
  asn1Item = new Container({
5734
5774
  name: "",
5735
- value: [
5736
- new Repeated({
5737
- name,
5738
- value: asn1Item
5739
- })
5740
- ]
5775
+ value: [new Repeated({ name, value: asn1Item })]
5741
5776
  });
5742
5777
  }
5743
5778
  if (item.context !== null && item.context !== void 0) {
5744
5779
  if (item.implicit) {
5745
5780
  if (typeof item.type === "number" || isConvertible(item.type)) {
5746
5781
  const Container = item.repeated ? Constructed : Primitive;
5747
- asn1Value.push(new Container({
5748
- name,
5749
- optional,
5750
- idBlock: {
5751
- tagClass: 3,
5752
- tagNumber: item.context
5753
- }
5754
- }));
5782
+ asn1Value.push(new Container({ name, optional, idBlock: { tagClass: 3, tagNumber: item.context } }));
5755
5783
  } else {
5756
5784
  this.cache(item.type);
5757
5785
  const isRepeated = !!item.repeated;
@@ -5760,20 +5788,14 @@ var AsnSchemaStorage = class {
5760
5788
  asn1Value.push(new Constructed({
5761
5789
  name: !isRepeated ? name : "",
5762
5790
  optional,
5763
- idBlock: {
5764
- tagClass: 3,
5765
- tagNumber: item.context
5766
- },
5791
+ idBlock: { tagClass: 3, tagNumber: item.context },
5767
5792
  value
5768
5793
  }));
5769
5794
  }
5770
5795
  } else {
5771
5796
  asn1Value.push(new Constructed({
5772
5797
  optional,
5773
- idBlock: {
5774
- tagClass: 3,
5775
- tagNumber: item.context
5776
- },
5798
+ idBlock: { tagClass: 3, tagNumber: item.context },
5777
5799
  value: [asn1Item]
5778
5800
  }));
5779
5801
  }
@@ -5829,7 +5851,6 @@ var AsnParser = class {
5829
5851
  return res;
5830
5852
  }
5831
5853
  static fromASN(asn1Schema, target) {
5832
- var _a2;
5833
5854
  try {
5834
5855
  if (isConvertible(target)) {
5835
5856
  const value = new target();
@@ -5838,104 +5859,259 @@ var AsnParser = class {
5838
5859
  const schema = schemaStorage.get(target);
5839
5860
  schemaStorage.cache(target);
5840
5861
  let targetSchema = schema.schema;
5841
- if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
5842
- targetSchema = new Constructed({
5843
- idBlock: {
5844
- tagClass: 3,
5845
- tagNumber: asn1Schema.idBlock.tagNumber
5846
- },
5847
- value: schema.schema.valueBlock.value
5848
- });
5849
- for (const key in schema.items) {
5850
- delete asn1Schema[key];
5851
- }
5862
+ const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema);
5863
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.result) {
5864
+ return choiceResult.result;
5852
5865
  }
5853
- const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
5854
- if (!asn1ComparedSchema.verified) {
5855
- throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`);
5866
+ if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.targetSchema) {
5867
+ targetSchema = choiceResult.targetSchema;
5856
5868
  }
5869
+ const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
5857
5870
  const res = new target();
5858
5871
  if (isTypeOfArray(target)) {
5859
- if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
5860
- throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
5861
- }
5862
- const itemType = schema.itemType;
5863
- if (typeof itemType === "number") {
5864
- const converter = defaultConverter(itemType);
5865
- if (!converter) {
5866
- throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
5867
- }
5868
- return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
5869
- } else {
5870
- return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
5871
- }
5872
+ return this.handleArrayTypes(asn1Schema, schema, target);
5873
+ }
5874
+ this.processSchemaItems(schema, sequenceResult, res);
5875
+ return res;
5876
+ } catch (error) {
5877
+ if (error instanceof AsnSchemaValidationError) {
5878
+ error.schemas.push(target.name);
5872
5879
  }
5880
+ throw error;
5881
+ }
5882
+ }
5883
+ static handleChoiceTypes(asn1Schema, schema, target, targetSchema) {
5884
+ if (asn1Schema.constructor === Constructed && schema.type === AsnTypeTypes.Choice && asn1Schema.idBlock.tagClass === 3) {
5873
5885
  for (const key in schema.items) {
5874
- const asn1SchemaValue = asn1ComparedSchema.result[key];
5875
- if (!asn1SchemaValue) {
5876
- continue;
5877
- }
5878
5886
  const schemaItem = schema.items[key];
5879
- const schemaItemType = schemaItem.type;
5880
- if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
5881
- const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
5882
- if (!converter) {
5883
- throw new Error("Converter is empty");
5884
- }
5885
- if (schemaItem.repeated) {
5886
- if (schemaItem.implicit) {
5887
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
5888
- const newItem = new Container();
5889
- newItem.valueBlock = asn1SchemaValue.valueBlock;
5890
- const newItemAsn = fromBER(newItem.toBER(false));
5891
- if (newItemAsn.offset === -1) {
5892
- throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
5893
- }
5894
- if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
5895
- throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
5896
- }
5897
- const value = newItemAsn.result.valueBlock.value;
5898
- res[key] = Array.from(value, (element) => converter.fromASN(element));
5899
- } else {
5900
- res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
5901
- }
5902
- } else {
5903
- let value = asn1SchemaValue;
5904
- if (schemaItem.implicit) {
5905
- let newItem;
5906
- if (isConvertible(schemaItemType)) {
5907
- newItem = new schemaItemType().toSchema("");
5908
- } else {
5909
- const Asn1TypeName = AsnPropTypes[schemaItemType];
5910
- const Asn1Type = index_es_exports[Asn1TypeName];
5911
- if (!Asn1Type) {
5912
- throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
5913
- }
5914
- newItem = new Asn1Type();
5887
+ if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
5888
+ if (typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type)) {
5889
+ const fieldSchema = schemaStorage.get(schemaItem.type);
5890
+ if (fieldSchema && fieldSchema.type === AsnTypeTypes.Sequence) {
5891
+ const newSeq = new Sequence();
5892
+ if ("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value) && "value" in newSeq.valueBlock) {
5893
+ newSeq.valueBlock.value = asn1Schema.valueBlock.value;
5894
+ const fieldValue = this.fromASN(newSeq, schemaItem.type);
5895
+ const res = new target();
5896
+ res[key] = fieldValue;
5897
+ return { result: res };
5915
5898
  }
5916
- newItem.valueBlock = value.valueBlock;
5917
- value = fromBER(newItem.toBER(false)).result;
5918
5899
  }
5919
- res[key] = converter.fromASN(value);
5920
5900
  }
5921
- } else {
5922
- if (schemaItem.repeated) {
5923
- if (!Array.isArray(asn1SchemaValue)) {
5924
- throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
5925
- }
5926
- res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
5927
- } else {
5928
- res[key] = this.fromASN(asn1SchemaValue, schemaItemType);
5901
+ }
5902
+ }
5903
+ } else if (asn1Schema.constructor === Constructed && schema.type !== AsnTypeTypes.Choice) {
5904
+ const newTargetSchema = new Constructed({
5905
+ idBlock: {
5906
+ tagClass: 3,
5907
+ tagNumber: asn1Schema.idBlock.tagNumber
5908
+ },
5909
+ value: schema.schema.valueBlock.value
5910
+ });
5911
+ for (const key in schema.items) {
5912
+ delete asn1Schema[key];
5913
+ }
5914
+ return { targetSchema: newTargetSchema };
5915
+ }
5916
+ return null;
5917
+ }
5918
+ static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
5919
+ if (schema.type === AsnTypeTypes.Sequence) {
5920
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
5921
+ if (!asn1ComparedSchema.verified) {
5922
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
5923
+ }
5924
+ return asn1ComparedSchema;
5925
+ } else {
5926
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
5927
+ if (!asn1ComparedSchema.verified) {
5928
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
5929
+ }
5930
+ return asn1ComparedSchema;
5931
+ }
5932
+ }
5933
+ static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
5934
+ let elementsToProcess = asn1Elements.slice(asn1Index);
5935
+ if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
5936
+ const seq = elementsToProcess[0];
5937
+ if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
5938
+ elementsToProcess = seq.valueBlock.value;
5939
+ }
5940
+ }
5941
+ if (typeof schemaItem.type === "number") {
5942
+ const converter = defaultConverter(schemaItem.type);
5943
+ if (!converter)
5944
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
5945
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
5946
+ try {
5947
+ return converter.fromASN(el);
5948
+ } catch {
5949
+ return void 0;
5950
+ }
5951
+ }).filter((v) => v !== void 0);
5952
+ } else {
5953
+ return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
5954
+ try {
5955
+ return this.fromASN(el, schemaItem.type);
5956
+ } catch {
5957
+ return void 0;
5958
+ }
5959
+ }).filter((v) => v !== void 0);
5960
+ }
5961
+ }
5962
+ static processPrimitiveField(asn1Element, schemaItem) {
5963
+ const converter = defaultConverter(schemaItem.type);
5964
+ if (!converter)
5965
+ throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
5966
+ return converter.fromASN(asn1Element);
5967
+ }
5968
+ static isOptionalChoiceField(schemaItem) {
5969
+ return schemaItem.optional && typeof schemaItem.type === "function" && schemaStorage.has(schemaItem.type) && schemaStorage.get(schemaItem.type).type === AsnTypeTypes.Choice;
5970
+ }
5971
+ static processOptionalChoiceField(asn1Element, schemaItem) {
5972
+ try {
5973
+ const value = this.fromASN(asn1Element, schemaItem.type);
5974
+ return { processed: true, value };
5975
+ } catch (err) {
5976
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
5977
+ return { processed: false };
5978
+ }
5979
+ throw err;
5980
+ }
5981
+ }
5982
+ static handleArrayTypes(asn1Schema, schema, target) {
5983
+ if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
5984
+ throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
5985
+ }
5986
+ const itemType = schema.itemType;
5987
+ if (typeof itemType === "number") {
5988
+ const converter = defaultConverter(itemType);
5989
+ if (!converter) {
5990
+ throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
5991
+ }
5992
+ return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
5993
+ } else {
5994
+ return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
5995
+ }
5996
+ }
5997
+ static processSchemaItems(schema, asn1ComparedSchema, res) {
5998
+ for (const key in schema.items) {
5999
+ const asn1SchemaValue = asn1ComparedSchema.result[key];
6000
+ if (!asn1SchemaValue) {
6001
+ continue;
6002
+ }
6003
+ const schemaItem = schema.items[key];
6004
+ const schemaItemType = schemaItem.type;
6005
+ let parsedValue;
6006
+ if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
6007
+ parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6008
+ } else {
6009
+ parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
6010
+ }
6011
+ if (parsedValue && typeof parsedValue === "object" && "value" in parsedValue && "raw" in parsedValue) {
6012
+ res[key] = parsedValue.value;
6013
+ res[`${key}Raw`] = parsedValue.raw;
6014
+ } else {
6015
+ res[key] = parsedValue;
6016
+ }
6017
+ }
6018
+ }
6019
+ static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6020
+ var _a2;
6021
+ const converter = (_a2 = schemaItem.converter) !== null && _a2 !== void 0 ? _a2 : isConvertible(schemaItemType) ? new schemaItemType() : null;
6022
+ if (!converter) {
6023
+ throw new Error("Converter is empty");
6024
+ }
6025
+ if (schemaItem.repeated) {
6026
+ return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter);
6027
+ } else {
6028
+ return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter);
6029
+ }
6030
+ }
6031
+ static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter) {
6032
+ if (schemaItem.implicit) {
6033
+ const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
6034
+ const newItem = new Container();
6035
+ newItem.valueBlock = asn1SchemaValue.valueBlock;
6036
+ const newItemAsn = fromBER(newItem.toBER(false));
6037
+ if (newItemAsn.offset === -1) {
6038
+ throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
6039
+ }
6040
+ if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
6041
+ throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
6042
+ }
6043
+ const value = newItemAsn.result.valueBlock.value;
6044
+ return Array.from(value, (element) => converter.fromASN(element));
6045
+ } else {
6046
+ return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
6047
+ }
6048
+ }
6049
+ static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter) {
6050
+ let value = asn1SchemaValue;
6051
+ if (schemaItem.implicit) {
6052
+ let newItem;
6053
+ if (isConvertible(schemaItemType)) {
6054
+ newItem = new schemaItemType().toSchema("");
6055
+ } else {
6056
+ const Asn1TypeName = AsnPropTypes[schemaItemType];
6057
+ const Asn1Type = index_es_exports[Asn1TypeName];
6058
+ if (!Asn1Type) {
6059
+ throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
6060
+ }
6061
+ newItem = new Asn1Type();
6062
+ }
6063
+ newItem.valueBlock = value.valueBlock;
6064
+ value = fromBER(newItem.toBER(false)).result;
6065
+ }
6066
+ return converter.fromASN(value);
6067
+ }
6068
+ static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
6069
+ if (schemaItem.repeated) {
6070
+ if (!Array.isArray(asn1SchemaValue)) {
6071
+ throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
6072
+ }
6073
+ return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
6074
+ } else {
6075
+ const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
6076
+ if (this.isOptionalChoiceField(schemaItem)) {
6077
+ try {
6078
+ return this.fromASN(valueToProcess, schemaItemType);
6079
+ } catch (err) {
6080
+ if (err instanceof AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
6081
+ return void 0;
5929
6082
  }
6083
+ throw err;
5930
6084
  }
6085
+ } else {
6086
+ const parsedValue = this.fromASN(valueToProcess, schemaItemType);
6087
+ if (schemaItem.raw) {
6088
+ return {
6089
+ value: parsedValue,
6090
+ raw: asn1SchemaValue.valueBeforeDecodeView
6091
+ };
6092
+ }
6093
+ return parsedValue;
5931
6094
  }
5932
- return res;
5933
- } catch (error) {
5934
- if (error instanceof AsnSchemaValidationError) {
5935
- error.schemas.push(target.name);
6095
+ }
6096
+ }
6097
+ static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
6098
+ if (schemaItem.implicit && typeof schemaItem.context === "number") {
6099
+ const schema = schemaStorage.get(schemaItemType);
6100
+ if (schema.type === AsnTypeTypes.Sequence) {
6101
+ const newSeq = new Sequence();
6102
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSeq.valueBlock) {
6103
+ newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
6104
+ return newSeq;
6105
+ }
6106
+ } else if (schema.type === AsnTypeTypes.Set) {
6107
+ const newSet = new Set();
6108
+ if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSet.valueBlock) {
6109
+ newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
6110
+ return newSet;
6111
+ }
5936
6112
  }
5937
- throw error;
5938
6113
  }
6114
+ return asn1SchemaValue;
5939
6115
  }
5940
6116
  };
5941
6117
 
@@ -6117,9 +6293,19 @@ async function createSelfSignedCertificate({
6117
6293
  }
6118
6294
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6119
6295
  const alternativeNameExtensions = [];
6120
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6121
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6122
- applicationUri && alternativeNameExtensions.push({ type: "url", value: applicationUri });
6296
+ if (dns) {
6297
+ for (const d of dns) {
6298
+ alternativeNameExtensions.push({ type: "dns", value: d });
6299
+ }
6300
+ }
6301
+ if (ip) {
6302
+ for (const d of ip) {
6303
+ alternativeNameExtensions.push({ type: "ip", value: d });
6304
+ }
6305
+ }
6306
+ if (applicationUri) {
6307
+ alternativeNameExtensions.push({ type: "url", value: applicationUri });
6308
+ }
6123
6309
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6124
6310
  const s = new Subject(subject || "");
6125
6311
  const s1 = s.toStringInternal(", ");
@@ -6153,11 +6339,9 @@ var asn1 = { readDirectoryName, readTag, readStruct, readAlgorithmIdentifier, re
6153
6339
 
6154
6340
  export {
6155
6341
  __dirname,
6156
- readExtension,
6157
- readTbsCertificate,
6158
- exploreCertificate,
6159
- split_der,
6160
- combine_der,
6342
+ createPrivateKeyFromNodeJSCrypto,
6343
+ isKeyObject,
6344
+ CertificatePurpose,
6161
6345
  identifyPemType,
6162
6346
  removeTrailingLF,
6163
6347
  toPem,
@@ -6178,12 +6362,11 @@ export {
6178
6362
  coerceCertificatePem,
6179
6363
  extractPublicKeyFromCertificateSync,
6180
6364
  extractPublicKeyFromCertificate,
6181
- explorePrivateKey,
6182
- publicKeyAndPrivateKeyMatches,
6183
- certificateMatchesPrivateKey,
6184
- createPrivateKeyFromNodeJSCrypto,
6185
- isKeyObject,
6186
- CertificatePurpose,
6365
+ readExtension,
6366
+ readTbsCertificate,
6367
+ exploreCertificate,
6368
+ split_der,
6369
+ combine_der,
6187
6370
  rsaLengthPrivateKey,
6188
6371
  toPem2,
6189
6372
  coercePrivateKeyPem,
@@ -6208,8 +6391,11 @@ export {
6208
6391
  exploreCertificateRevocationList,
6209
6392
  readCertificationRequestInfo,
6210
6393
  exploreCertificateSigningRequest,
6394
+ explorePrivateKey,
6211
6395
  makePrivateKeyFromPem,
6212
6396
  makePrivateKeyThumbPrint,
6397
+ publicKeyAndPrivateKeyMatches,
6398
+ certificateMatchesPrivateKey,
6213
6399
  Subject,
6214
6400
  verifyCertificateOrClrSignature,
6215
6401
  verifyCertificateSignature,
@@ -6232,7 +6418,7 @@ pvtsutils/build/index.es.js:
6232
6418
  (*!
6233
6419
  * MIT License
6234
6420
  *
6235
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
6421
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
6236
6422
  *
6237
6423
  * Permission is hereby granted, free of charge, to any person obtaining a copy
6238
6424
  * of this software and associated documentation files (the "Software"), to deal
@@ -6294,4 +6480,4 @@ asn1js/build/index.es.js:
6294
6480
  *
6295
6481
  *)
6296
6482
  */
6297
- //# sourceMappingURL=chunk-F5EAPW2U.mjs.map
6483
+ //# sourceMappingURL=chunk-EURHGMEG.mjs.map