node-opcua-crypto 4.16.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,4 @@
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 });
@@ -17,6 +11,27 @@ 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
1163
  extensions = _readExtensions(buffer, extensionBlock);
943
1164
  }
944
1165
  }
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
- );
1233
- }
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
- return {
1243
- version,
1244
- modulus,
1245
- publicExponent,
1246
- privateExponent,
1247
- prime1,
1248
- prime2,
1249
- exponent1,
1250
- exponent2
1166
+ return {
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(", ");
@@ -6254,9 +6293,19 @@ async function createSelfSignedCertificate({
6254
6293
  }
6255
6294
  notAfter = notAfter || new Date(notBefore.getTime() + validity * 24 * 60 * 60 * 1e3);
6256
6295
  const alternativeNameExtensions = [];
6257
- dns && dns.forEach((d) => alternativeNameExtensions.push({ type: "dns", value: d }));
6258
- ip && ip.forEach((d) => alternativeNameExtensions.push({ type: "ip", value: d }));
6259
- 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
+ }
6260
6309
  const ID_NETSCAPE_COMMENT = "2.16.840.1.113730.1.13";
6261
6310
  const s = new Subject(subject || "");
6262
6311
  const s1 = s.toStringInternal(", ");
@@ -6290,11 +6339,9 @@ var asn1 = { readDirectoryName, readTag, readStruct, readAlgorithmIdentifier, re
6290
6339
 
6291
6340
  export {
6292
6341
  __dirname,
6293
- readExtension,
6294
- readTbsCertificate,
6295
- exploreCertificate,
6296
- split_der,
6297
- combine_der,
6342
+ createPrivateKeyFromNodeJSCrypto,
6343
+ isKeyObject,
6344
+ CertificatePurpose,
6298
6345
  identifyPemType,
6299
6346
  removeTrailingLF,
6300
6347
  toPem,
@@ -6315,12 +6362,11 @@ export {
6315
6362
  coerceCertificatePem,
6316
6363
  extractPublicKeyFromCertificateSync,
6317
6364
  extractPublicKeyFromCertificate,
6318
- explorePrivateKey,
6319
- publicKeyAndPrivateKeyMatches,
6320
- certificateMatchesPrivateKey,
6321
- createPrivateKeyFromNodeJSCrypto,
6322
- isKeyObject,
6323
- CertificatePurpose,
6365
+ readExtension,
6366
+ readTbsCertificate,
6367
+ exploreCertificate,
6368
+ split_der,
6369
+ combine_der,
6324
6370
  rsaLengthPrivateKey,
6325
6371
  toPem2,
6326
6372
  coercePrivateKeyPem,
@@ -6345,8 +6391,11 @@ export {
6345
6391
  exploreCertificateRevocationList,
6346
6392
  readCertificationRequestInfo,
6347
6393
  exploreCertificateSigningRequest,
6394
+ explorePrivateKey,
6348
6395
  makePrivateKeyFromPem,
6349
6396
  makePrivateKeyThumbPrint,
6397
+ publicKeyAndPrivateKeyMatches,
6398
+ certificateMatchesPrivateKey,
6350
6399
  Subject,
6351
6400
  verifyCertificateOrClrSignature,
6352
6401
  verifyCertificateSignature,
@@ -6431,4 +6480,4 @@ asn1js/build/index.es.js:
6431
6480
  *
6432
6481
  *)
6433
6482
  */
6434
- //# sourceMappingURL=chunk-MGQCHN54.mjs.map
6483
+ //# sourceMappingURL=chunk-BIS3W2GR.mjs.map