micro509 0.9.0 → 0.11.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.
Files changed (111) hide show
  1. package/dist/index.d.ts +5 -4
  2. package/dist/index.js +16 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +583 -547
  47. package/dist/keys/keys.js +519 -431
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.js +2 -2
  50. package/dist/pem/pem.d.ts +46 -46
  51. package/dist/pem/pem.js +62 -81
  52. package/dist/pem/pem.js.map +1 -0
  53. package/dist/pem.js +2 -2
  54. package/dist/pkcs/pfx.d.ts +96 -80
  55. package/dist/pkcs/pfx.js +191 -231
  56. package/dist/pkcs/pfx.js.map +1 -0
  57. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  58. package/dist/pkcs/pkcs12-mac.js +90 -111
  59. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  60. package/dist/pkcs/pkcs7.d.ts +118 -69
  61. package/dist/pkcs/pkcs7.js +401 -443
  62. package/dist/pkcs/pkcs7.js.map +1 -0
  63. package/dist/pkcs.d.ts +2 -2
  64. package/dist/pkcs.js +4 -4
  65. package/dist/result/result.d.ts +37 -32
  66. package/dist/result/result.js +46 -44
  67. package/dist/result/result.js.map +1 -0
  68. package/dist/result.js +2 -2
  69. package/dist/revocation/chain.d.ts +138 -119
  70. package/dist/revocation/chain.js +248 -281
  71. package/dist/revocation/chain.js.map +1 -0
  72. package/dist/revocation/crl.d.ts +125 -123
  73. package/dist/revocation/crl.js +653 -745
  74. package/dist/revocation/crl.js.map +1 -0
  75. package/dist/revocation/ocsp.d.ts +183 -177
  76. package/dist/revocation/ocsp.js +579 -636
  77. package/dist/revocation/ocsp.js.map +1 -0
  78. package/dist/revocation/revocation.d.ts +26 -26
  79. package/dist/revocation/revocation.js +104 -125
  80. package/dist/revocation/revocation.js.map +1 -0
  81. package/dist/revocation.js +5 -5
  82. package/dist/verify/identity.d.ts +42 -42
  83. package/dist/verify/identity.js +158 -167
  84. package/dist/verify/identity.js.map +1 -0
  85. package/dist/verify/name-constraints.d.ts +7 -7
  86. package/dist/verify/policy.d.ts +10 -10
  87. package/dist/verify/verify.d.ts +163 -163
  88. package/dist/verify/verify.js +396 -392
  89. package/dist/verify/verify.js.map +1 -0
  90. package/dist/verify.js +3 -3
  91. package/dist/x509/certificate.d.ts +117 -117
  92. package/dist/x509/certificate.js +51 -60
  93. package/dist/x509/certificate.js.map +1 -0
  94. package/dist/x509/csr.d.ts +25 -25
  95. package/dist/x509/csr.js +26 -30
  96. package/dist/x509/csr.js.map +1 -0
  97. package/dist/x509/extensions.d.ts +228 -184
  98. package/dist/x509/extensions.js +175 -200
  99. package/dist/x509/extensions.js.map +1 -0
  100. package/dist/x509/fingerprint.d.ts +55 -0
  101. package/dist/x509/fingerprint.js +55 -0
  102. package/dist/x509/fingerprint.js.map +1 -0
  103. package/dist/x509/name.d.ts +94 -93
  104. package/dist/x509/name.js +30 -29
  105. package/dist/x509/name.js.map +1 -0
  106. package/dist/x509/parse.d.ts +288 -185
  107. package/dist/x509/parse.js +762 -677
  108. package/dist/x509/parse.js.map +1 -0
  109. package/dist/x509.d.ts +3 -2
  110. package/dist/x509.js +7 -6
  111. package/package.json +79 -41
@@ -1,16 +1,16 @@
1
- import { concatBytes, explicitContext, integer, integerFromNumber, nullValue, objectIdentifier, octetString, readElement, readRootElement, readSequenceChildren, sequence, setOf } from "../internal/asn1/der.js";
2
- import { childrenOf, decodeIntegerNumber, decodeObjectIdentifier, decodeString, hexToBytes, requireElement, toArrayBuffer, toHex } from "../internal/asn1/asn1.js";
3
- import { OIDS } from "../internal/asn1/oids.js";
4
- import { getCrypto } from "../internal/crypto/webcrypto.js";
5
- import { base64Encode } from "../internal/shared/base64.js";
6
- import { failureResult } from "../result/result.js";
7
- import { pemEncode, splitPemBlocksOrThrow } from "../pem/pem.js";
8
- import { describeHashAlgorithm, describeSignatureAlgorithm } from "../internal/crypto/algorithm-names.js";
9
- import { nameFieldKeyFromOid } from "../internal/x509/name-fields.js";
10
- import { parseCertificateDerOrThrow } from "../x509/parse.js";
11
- import { verifySignedDataDetailed } from "../internal/crypto/sig-verify.js";
12
- import { encodeAlgorithmIdentifier, getSignatureAlgorithm, signBytes } from "../internal/crypto/signing.js";
13
- import { compareDistinguishedNames } from "../internal/shared/dn.js";
1
+ import { concatBytes as e, explicitContext as t, integer as n, integerFromNumber as r, nullValue as i, objectIdentifier as a, octetString as o, readElement as s, readRootElement as c, readSequenceChildren as l, sequence as u, setOf as d } from "../internal/asn1/der.js";
2
+ import { childrenOf as f, decodeIntegerNumber as p, decodeObjectIdentifier as m, decodeString as h, hexToBytes as g, requireElement as _, toArrayBuffer as v, toHex as y } from "../internal/asn1/asn1.js";
3
+ import { OIDS as b } from "../internal/asn1/oids2.js";
4
+ import { getCrypto as x } from "../internal/crypto/webcrypto.js";
5
+ import { base64Encode as S } from "../internal/shared/base64.js";
6
+ import { failureResult as C } from "../result/result.js";
7
+ import { pemEncode as w, splitPemBlocksOrThrow as T } from "../pem/pem.js";
8
+ import { describeHashAlgorithm as E, describeSignatureAlgorithm as D } from "../internal/crypto/algorithm-names.js";
9
+ import { nameFieldKeyFromOid as O } from "../internal/x509/name-fields.js";
10
+ import { parseCertificateDerOrThrow as k } from "../x509/parse.js";
11
+ import { verifySignedDataDetailed as A } from "../internal/crypto/sig-verify.js";
12
+ import { encodeAlgorithmIdentifier as j, getSignatureAlgorithm as M, signBytes as N } from "../internal/crypto/signing.js";
13
+ import { compareDistinguishedNames as P } from "../internal/shared/dn.js";
14
14
  //#region src/pkcs/pkcs7.ts
15
15
  /**
16
16
  * PKCS#7/CMS certificate bags and SignedData.
@@ -26,27 +26,26 @@ import { compareDistinguishedNames } from "../internal/shared/dn.js";
26
26
  * typed `invalid_certificate` failure when a certificate source is not
27
27
  * valid PEM/DER.
28
28
  */
29
- function createPkcs7CertBag(certificates) {
30
- let certificateDers;
29
+ function createPkcs7CertBag(n) {
30
+ let i;
31
31
  try {
32
- certificateDers = certificates.flatMap(normalizeCertificateSource);
32
+ i = n.flatMap(normalizeCertificateSource);
33
33
  } catch {
34
34
  return createCertBagFailure("invalid_certificate", "Each PKCS#7 certificate source must be valid PEM or DER");
35
35
  }
36
- const signedData = sequence([
37
- integerFromNumber(1),
38
- setOf([]),
39
- sequence([objectIdentifier(OIDS.pkcs7Data)]),
40
- explicitContext(0, concatBytes(certificateDers)),
41
- setOf([])
42
- ]);
43
- const der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);
36
+ let o = u([
37
+ r(1),
38
+ d([]),
39
+ u([a(b.pkcs7Data)]),
40
+ t(0, e(i)),
41
+ d([])
42
+ ]), s = u([a(b.pkcs7SignedData), t(0, o)]);
44
43
  return {
45
- ok: true,
44
+ ok: !0,
46
45
  value: {
47
- der,
48
- pem: pemEncode("PKCS7", der),
49
- base64: base64Encode(der)
46
+ der: s,
47
+ pem: w("PKCS7", s),
48
+ base64: S(s)
50
49
  }
51
50
  };
52
51
  }
@@ -55,9 +54,11 @@ function createPkcs7CertBag(certificates) {
55
54
  *
56
55
  * Each signer uses the RFC 5652 Section 5.4 signed-attributes flow: the
57
56
  * signature covers a `SET OF` authenticated attributes carrying `contentType`
58
- * and `messageDigest` (the digest of the encapsulated content). The content is
59
- * embedded (attached signature), so the result verifies with
60
- * {@linkcode verifyPkcs7SignedData} without any external data.
57
+ * and `messageDigest` (the digest of the encapsulated content). By default the
58
+ * content is embedded (attached signature), so the result verifies with
59
+ * {@linkcode verifyPkcs7SignedData} without any external data. With
60
+ * `detached: true` the `eContent` is omitted (RFC 5652 Section 5.2) and the
61
+ * verifier must supply the content externally.
61
62
  *
62
63
  * The content digest is derived from each signer's key (P-256/RSA-SHA256 →
63
64
  * SHA-256, P-384 → SHA-384, P-521 → SHA-512, Ed25519 → SHA-512 per RFC 8419).
@@ -67,158 +68,166 @@ function createPkcs7CertBag(certificates) {
67
68
  * signers, a signer source that is not exactly one certificate, or an
68
69
  * unsupported signer key).
69
70
  */
70
- async function createPkcs7SignedData(input) {
71
- if (input.signers.length === 0) return createPkcs7Failure("no_signers", "createPkcs7SignedData requires at least one signer");
72
- const encapsulatedContentTypeOid = input.encapsulatedContentTypeOid ?? OIDS.pkcs7Data;
73
- const content = input.content.slice();
74
- const certificateDers = [];
75
- const seenCertificates = /* @__PURE__ */ new Set();
76
- const addCertificate = (der) => {
77
- const hex = toHex(der);
78
- if (!seenCertificates.has(hex)) {
79
- seenCertificates.add(hex);
80
- certificateDers.push(der);
81
- }
82
- };
83
- const digestAlgorithmOids = /* @__PURE__ */ new Set();
84
- const signerInfos = [];
85
- for (const signer of input.signers) {
86
- const signerCertDers = normalizeCertificateSource(signer.certificate);
87
- const signerCertDer = signerCertDers[0];
88
- if (signerCertDer === void 0 || signerCertDers.length !== 1) return createPkcs7Failure("invalid_signer_certificate", "Each PKCS#7 signer must provide exactly one certificate");
89
- addCertificate(signerCertDer);
90
- let certificate;
91
- try {
92
- certificate = parseCertificateDerOrThrow(signerCertDer);
93
- } catch {
94
- return createPkcs7Failure("invalid_signer_certificate", "Each PKCS#7 signer certificate must be a parseable X.509 certificate");
95
- }
96
- let signatureAlgorithm;
97
- try {
98
- signatureAlgorithm = getSignatureAlgorithm(signer.privateKey, signer.signature);
99
- } catch {
100
- return createPkcs7Failure("unsupported_signer_key", "Unsupported signer key or signature profile");
101
- }
102
- const digest = contentDigestForPrivateKey(signer.privateKey);
103
- if (digest === void 0) return createPkcs7Failure("unsupported_signer_key", "Unsupported signer key algorithm for content digest");
104
- digestAlgorithmOids.add(digest.digestOid);
105
- const { setForSigning, implicitForEmit } = buildSignedAttributes(encapsulatedContentTypeOid, new Uint8Array(await getCrypto().subtle.digest(digest.hashName, toArrayBuffer(content))));
106
- const signature = await signBytes(signer.privateKey, signatureAlgorithm, setForSigning);
107
- signerInfos.push(sequence([
108
- integerFromNumber(1),
109
- sequence([hexToBytes(certificate.issuer.derHex), integer(hexToBytes(certificate.serialNumberHex))]),
110
- sequence([objectIdentifier(digest.digestOid), nullValue()]),
111
- implicitForEmit,
112
- encodeAlgorithmIdentifier(signatureAlgorithm),
113
- octetString(signature)
114
- ]));
71
+ async function createPkcs7SignedData(e) {
72
+ if (e.signers.length === 0) return createPkcs7Failure("no_signers", "createPkcs7SignedData requires at least one signer");
73
+ let n = e.encapsulatedContentTypeOid ?? b.pkcs7Data, s = e.content.slice(), c = [], l = /* @__PURE__ */ new Set(), addCertificate = (e) => {
74
+ let t = y(e);
75
+ l.has(t) || (l.add(t), c.push(e));
76
+ }, f = /* @__PURE__ */ new Set(), p = [];
77
+ for (let t of e.signers) {
78
+ let e = await buildPkcs7SignerInfo(t, s, n);
79
+ if (!e.ok) return e;
80
+ addCertificate(e.certificateDer), f.add(e.digestOid), p.push(e.signerInfoDer);
115
81
  }
116
- for (const source of input.additionalCertificates ?? []) for (const der of normalizeCertificateSource(source)) addCertificate(der);
117
- const signedDataVersion = encapsulatedContentTypeOid === OIDS.pkcs7Data ? 1 : 3;
118
- const certificateSet = new Uint8Array(setOf(certificateDers));
119
- certificateSet[0] = 160;
120
- const signedData = sequence([
121
- integerFromNumber(signedDataVersion),
122
- setOf([...digestAlgorithmOids].map((oid) => sequence([objectIdentifier(oid), nullValue()]))),
123
- sequence([objectIdentifier(encapsulatedContentTypeOid), explicitContext(0, octetString(content))]),
124
- certificateSet,
125
- setOf(signerInfos)
126
- ]);
127
- const der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);
82
+ for (let t of e.additionalCertificates ?? []) try {
83
+ for (let e of normalizeCertificateSource(t)) k(e), addCertificate(e);
84
+ } catch {
85
+ return createPkcs7Failure("invalid_certificate", "Each additional PKCS#7 certificate source must be valid PEM or DER");
86
+ }
87
+ let m = n === b.pkcs7Data ? 1 : 3, h = new Uint8Array(d(c));
88
+ h[0] = 160;
89
+ let g = u([
90
+ r(m),
91
+ d([...f].map((e) => u([a(e), i()]))),
92
+ e.detached === !0 ? u([a(n)]) : u([a(n), t(0, o(s))]),
93
+ h,
94
+ d(p)
95
+ ]), _ = u([a(b.pkcs7SignedData), t(0, g)]);
128
96
  return {
129
- ok: true,
97
+ ok: !0,
130
98
  value: {
131
- der,
132
- pem: pemEncode("PKCS7", der),
133
- base64: base64Encode(der)
99
+ der: _,
100
+ pem: w("PKCS7", _),
101
+ base64: S(_)
134
102
  }
135
103
  };
136
104
  }
137
- /** Parses a DER-encoded PKCS#7 cert bag, returning the contained certificates. */
138
- function parsePkcs7CertBagDer(der) {
139
- const result = parsePkcs7SignedDataDer(der);
140
- if (!result.ok) return result;
105
+ /**
106
+ * Builds one signer's SignerInfo over `content` (RFC 5652 Section 5.4
107
+ * signed-attributes flow). Every throwing step here reacts to
108
+ * caller-correctable input — malformed PEM/DER, unsupported key — so each is
109
+ * mapped to a typed failure rather than rejecting the public Promise.
110
+ */
111
+ async function buildPkcs7SignerInfo(e, t, s) {
112
+ let c;
113
+ try {
114
+ c = normalizeCertificateSource(e.certificate);
115
+ } catch {
116
+ return createPkcs7Failure("invalid_signer_certificate", "Each PKCS#7 signer certificate source must be valid PEM or DER");
117
+ }
118
+ let l = c[0];
119
+ if (l === void 0 || c.length !== 1) return createPkcs7Failure("invalid_signer_certificate", "Each PKCS#7 signer must provide exactly one certificate");
120
+ let d;
121
+ try {
122
+ d = k(l);
123
+ } catch {
124
+ return createPkcs7Failure("invalid_signer_certificate", "Each PKCS#7 signer certificate must be a parseable X.509 certificate");
125
+ }
126
+ let f;
127
+ try {
128
+ f = M(e.privateKey, e.signature);
129
+ } catch {
130
+ return createPkcs7Failure("unsupported_signer_key", "Unsupported signer key or signature profile");
131
+ }
132
+ let p = contentDigestForPrivateKey(e.privateKey);
133
+ if (p === void 0) return createPkcs7Failure("unsupported_signer_key", "Unsupported signer key algorithm for content digest");
134
+ let { setForSigning: m, implicitForEmit: h } = buildSignedAttributes(s, new Uint8Array(await x().subtle.digest(p.hashName, v(t)))), _;
135
+ try {
136
+ _ = await N(e.privateKey, f, m);
137
+ } catch {
138
+ return createPkcs7Failure("unsupported_signer_key", "Signer key could not produce a PKCS#7 signature");
139
+ }
141
140
  return {
142
- ok: true,
143
- value: result.value.certificates
141
+ ok: !0,
142
+ signerInfoDer: u([
143
+ r(1),
144
+ u([g(d.issuer.derHex), n(g(d.serialNumberHex))]),
145
+ u([a(p.digestOid), i()]),
146
+ h,
147
+ j(f),
148
+ o(_)
149
+ ]),
150
+ digestOid: p.digestOid,
151
+ certificateDer: l
144
152
  };
145
153
  }
154
+ /** Parses a DER-encoded PKCS#7 cert bag, returning the contained certificates. */
155
+ function parsePkcs7CertBagDer(e) {
156
+ let t = parsePkcs7SignedDataDer(e);
157
+ return t.ok ? {
158
+ ok: !0,
159
+ value: t.value.certificates
160
+ } : t;
161
+ }
146
162
  /** Parses a PEM-armored PKCS#7 cert bag. Expects exactly one `PKCS7` PEM block. */
147
- function parsePkcs7CertBagPem(pem) {
163
+ function parsePkcs7CertBagPem(e) {
148
164
  try {
149
- const blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === "PKCS7");
150
- if (blocks.length !== 1) return pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block");
151
- const block = blocks[0];
152
- if (block === void 0) return pkcs7Failure("malformed", "Missing PKCS7 block");
153
- return parsePkcs7CertBagDer(block.bytes);
165
+ let t = T(e).filter((e) => e.label === "PKCS7");
166
+ if (t.length !== 1) return pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block");
167
+ let n = t[0];
168
+ return n === void 0 ? pkcs7Failure("malformed", "Missing PKCS7 block") : parsePkcs7CertBagDer(n.bytes);
154
169
  } catch {
155
170
  return pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block");
156
171
  }
157
172
  }
158
173
  /** Decodes a DER-encoded PKCS#7 ContentInfo expecting `signedData` content type. */
159
- function parsePkcs7SignedDataDer(der) {
174
+ function parsePkcs7SignedDataDer(e) {
160
175
  try {
161
- const contentInfo = readSequenceChildren(der, { maxDepth: 64 });
162
- const contentType = contentInfo[0];
163
- const content = contentInfo[1];
164
- if (contentType === void 0 || content === void 0 || contentInfo.length !== 2 || contentType.tag !== 6 || content.tag !== 160) return pkcs7Failure("malformed", "Malformed PKCS#7 content info");
165
- if (childrenOf(der, content).length !== 1) return pkcs7Failure("malformed", "Malformed PKCS#7 content info");
166
- const contentTypeOid = decodeObjectIdentifier(contentType.value);
167
- if (contentTypeOid !== OIDS.pkcs7SignedData) return pkcs7Failure("not_signed_data", "PKCS#7 content is not signedData");
168
- const signedDataChildren = childrenOf(der, childAt(der, content, 0, "signedData"));
169
- const version = signedDataChildren[0];
170
- const digestAlgorithms = signedDataChildren[1];
171
- const encapContentInfo = signedDataChildren[2];
172
- const trailingChildren = signedDataChildren.slice(3);
173
- const signerInfos = trailingChildren[trailingChildren.length - 1];
174
- let certificates;
175
- let crls;
176
- for (const child of trailingChildren.slice(0, -1)) {
177
- if (child?.tag === 160) {
178
- if (crls !== void 0) return pkcs7Failure("malformed", "SignedData certificates field must precede CRLs field");
179
- if (certificates !== void 0) return pkcs7Failure("malformed", "SignedData certificates field must not repeat");
180
- certificates = child;
181
- continue;
182
- }
183
- if (child?.tag === 161) {
184
- if (crls !== void 0) return pkcs7Failure("malformed", "SignedData CRLs field must not repeat");
185
- crls = child;
186
- continue;
187
- }
188
- return pkcs7Failure("malformed", "Malformed SignedData optional field");
189
- }
190
- if (version === void 0 || digestAlgorithms === void 0 || encapContentInfo === void 0 || signerInfos === void 0 || signerInfos.tag !== 49) return pkcs7Failure("malformed", "Malformed SignedData");
191
- const encapDer = der.slice(encapContentInfo.start - encapContentInfo.headerLength, encapContentInfo.end);
192
- const encapChildren = readSequenceChildren(encapDer);
193
- const encapType = encapChildren[0];
194
- const encapContent = encapChildren[1];
195
- const digestAlgorithmOids = parseDigestAlgorithms(der, digestAlgorithms);
196
- if (encapType === void 0) return pkcs7Failure("malformed", "Malformed EncapsulatedContentInfo");
197
- return {
198
- ok: true,
176
+ let t = l(e, { maxDepth: 64 }), n = t[0], r = t[1];
177
+ if (n === void 0 || r === void 0 || t.length !== 2 || n.tag !== 6 || r.tag !== 160 || f(e, r).length !== 1) return pkcs7Failure("malformed", "Malformed PKCS#7 content info");
178
+ let i = m(n.value);
179
+ if (i !== b.pkcs7SignedData) return pkcs7Failure("not_signed_data", "PKCS#7 content is not signedData");
180
+ let a = f(e, childAt(e, r, 0, "signedData")), o = a[0], s = a[1], c = a[2], u = a.slice(3), d = u[u.length - 1], h = parseSignedDataOptionalFields(u.slice(0, -1));
181
+ if (!h.ok) return h;
182
+ if (o === void 0 || s === void 0 || c === void 0 || d === void 0 || d.tag !== 49) return pkcs7Failure("malformed", "Malformed SignedData");
183
+ let g = e.slice(c.start - c.headerLength, c.end), _ = l(g), v = _[0], y = _[1], x = parseDigestAlgorithms(e, s);
184
+ return v === void 0 ? pkcs7Failure("malformed", "Malformed EncapsulatedContentInfo") : {
185
+ ok: !0,
199
186
  value: {
200
- der: new Uint8Array(der),
201
- contentTypeOid,
202
- version: decodeIntegerNumber(version.value),
203
- digestAlgorithmOids,
204
- digestAlgorithmNames: digestAlgorithmOids.map((oid) => describeHashAlgorithm(oid)),
205
- encapsulatedContentTypeOid: decodeObjectIdentifier(encapType.value),
206
- ...encapContent === void 0 ? {} : { encapsulatedContent: extractEncapsulatedContent(encapDer, encapContent) },
207
- certificates: parseCertificateSet(der, certificates),
208
- signerInfos: parseSignerInfos(der, signerInfos)
187
+ der: new Uint8Array(e),
188
+ contentTypeOid: i,
189
+ version: p(o.value),
190
+ digestAlgorithmOids: x,
191
+ digestAlgorithmNames: x.map((e) => E(e)),
192
+ encapsulatedContentTypeOid: m(v.value),
193
+ ...y === void 0 ? {} : { encapsulatedContent: extractEncapsulatedContent(g, y) },
194
+ certificates: parseCertificateSet(e, h.value.certificates),
195
+ signerInfos: parseSignerInfos(e, d)
209
196
  }
210
197
  };
211
198
  } catch {
212
199
  return pkcs7Failure("malformed", "Malformed PKCS#7 structure");
213
200
  }
214
201
  }
202
+ function parseSignedDataOptionalFields(e) {
203
+ let t, n;
204
+ for (let r of e) {
205
+ if (r.tag === 160) {
206
+ if (n !== void 0) return pkcs7Failure("malformed", "SignedData certificates field must precede CRLs field");
207
+ if (t !== void 0) return pkcs7Failure("malformed", "SignedData certificates field must not repeat");
208
+ t = r;
209
+ continue;
210
+ }
211
+ if (r.tag === 161) {
212
+ if (n !== void 0) return pkcs7Failure("malformed", "SignedData CRLs field must not repeat");
213
+ n = r;
214
+ continue;
215
+ }
216
+ return pkcs7Failure("malformed", "Malformed SignedData optional field");
217
+ }
218
+ return {
219
+ ok: !0,
220
+ value: {
221
+ ...t === void 0 ? {} : { certificates: t },
222
+ ...n === void 0 ? {} : { crls: n }
223
+ }
224
+ };
225
+ }
215
226
  /** Decodes a PEM-armored PKCS#7 SignedData. Expects exactly one `PKCS7` PEM block. */
216
- function parsePkcs7SignedDataPem(pem) {
227
+ function parsePkcs7SignedDataPem(e) {
217
228
  try {
218
- const blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === "PKCS7");
219
- const block = blocks[0];
220
- if (block === void 0 || blocks.length !== 1) return pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block");
221
- return parsePkcs7SignedDataDer(block.bytes);
229
+ let t = T(e).filter((e) => e.label === "PKCS7"), n = t[0];
230
+ return n === void 0 || t.length !== 1 ? pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block") : parsePkcs7SignedDataDer(n.bytes);
222
231
  } catch {
223
232
  return pkcs7Failure("malformed", "Expected exactly one PKCS7 PEM block");
224
233
  }
@@ -230,6 +239,11 @@ function parsePkcs7SignedDataPem(pem) {
230
239
  * For each signer, locates the matching certificate in the embedded set and
231
240
  * verifies the signature (including signed-attribute digest checks per RFC 5652 Section 5.4).
232
241
  *
242
+ * For a detached SignedData (absent `eContent`), pass the externally-held
243
+ * content via `options.content`; without it, verification fails with the
244
+ * typed `detached_content_required` code. When the SignedData embeds its own
245
+ * content, that embedded content is verified and `options.content` is ignored.
246
+ *
233
247
  * @example
234
248
  * ```ts
235
249
  * import { verifyPkcs7SignedData } from 'micro509';
@@ -238,80 +252,69 @@ function parsePkcs7SignedDataPem(pem) {
238
252
  * if (result.ok) {
239
253
  * console.log('all signers verified');
240
254
  * }
255
+ *
256
+ * // Detached signature: supply the content externally
257
+ * const detached = await verifyPkcs7SignedData(cmsBlob, { content: signedBytes });
241
258
  * ```
242
259
  */
243
- async function verifyPkcs7SignedData(input) {
244
- let parsed;
245
- if (typeof input === "string") {
246
- const result = parsePkcs7SignedDataPem(input);
247
- if (!result.ok) return result;
248
- parsed = result.value;
249
- } else if (input instanceof Uint8Array) {
250
- const result = parsePkcs7SignedDataDer(input);
251
- if (!result.ok) return result;
252
- parsed = result.value;
253
- } else {
254
- if (!hasReparseablePkcs7SignedData(input)) return verifyPkcs7Failure("malformed", "SignedData parsed input is malformed");
255
- const result = parsePkcs7SignedDataDer(new Uint8Array(input.der));
256
- if (!result.ok) return result;
257
- parsed = result.value;
258
- }
259
- if (parsed.encapsulatedContent === void 0) return verifyPkcs7Failure("content_missing", "SignedData encapsulated content is missing");
260
- for (const signerInfo of parsed.signerInfos) {
261
- const signer = parsed.certificates.find((certificate) => signerIdentifierMatches(certificate, signerInfo));
262
- if (signer === void 0) return verifyPkcs7Failure("signer_not_found", "Signer certificate not found in SignedData certificates");
263
- if (signerInfo.hasSignedAttrs) {
264
- const attrsResult = await verifySignedAttrs(signerInfo, signer, parsed.encapsulatedContent, parsed.encapsulatedContentTypeOid);
265
- if (!attrsResult.ok) return attrsResult;
266
- continue;
267
- }
268
- let verified;
269
- try {
270
- const verificationResult = await verifySignedDataDetailed(signerInfo.signatureAlgorithmOid, signerInfo.signatureAlgorithmParametersDer, signer.publicKeyAlgorithmOid, signer.publicKeyParametersOid, signer.subjectPublicKeyInfoDer, signerInfo.signature, parsed.encapsulatedContent);
271
- if (!verificationResult.ok) {
272
- if (verificationResult.code === "verification_error") return verifyPkcs7Failure("malformed", "SignedData signature verification failed");
273
- return verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
274
- }
275
- verified = verificationResult.valid;
276
- } catch {
277
- return verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
278
- }
279
- if (!verified) return verifyPkcs7Failure("signature_invalid", "SignedData signature does not verify");
260
+ async function verifyPkcs7SignedData(e, t = {}) {
261
+ let n = normalizePkcs7SignedDataForVerification(e);
262
+ if (!n.ok) return n;
263
+ let r = n.value, i = r.encapsulatedContent ?? t.content?.slice();
264
+ if (i === void 0) return verifyPkcs7Failure("detached_content_required", "SignedData has no encapsulated content; supply the detached content via options.content");
265
+ for (let e of r.signerInfos) {
266
+ let t = await verifyPkcs7SignerInfo(r, e, i);
267
+ if (!t.ok) return t;
280
268
  }
281
269
  return {
282
- ok: true,
283
- value: parsed
270
+ ok: !0,
271
+ value: r
284
272
  };
285
273
  }
274
+ /** Normalizes encoded or parsed SignedData into a freshly parsed verification input. */
275
+ function normalizePkcs7SignedDataForVerification(e) {
276
+ return typeof e == "string" ? parsePkcs7SignedDataPem(e) : e instanceof Uint8Array ? parsePkcs7SignedDataDer(e) : hasReparseablePkcs7SignedData(e) ? parsePkcs7SignedDataDer(new Uint8Array(e.der)) : verifyPkcs7Failure("malformed", "SignedData parsed input is malformed");
277
+ }
278
+ /** Resolves and verifies one signer entry in a parsed PKCS#7 SignedData value. */
279
+ async function verifyPkcs7SignerInfo(e, t, n) {
280
+ let r = e.certificates.find((e) => signerIdentifierMatches(e, t));
281
+ return r === void 0 ? verifyPkcs7Failure("signer_not_found", "Signer certificate not found in SignedData certificates") : t.hasSignedAttrs ? await verifySignedAttrs(t, r, n, e.encapsulatedContentTypeOid) : await verifyPkcs7BareSignerInfo(t, r, n);
282
+ }
283
+ async function verifyPkcs7BareSignerInfo(e, t, n) {
284
+ try {
285
+ let r = await A(e.signatureAlgorithmOid, e.signatureAlgorithmParametersDer, t.publicKeyAlgorithmOid, t.publicKeyParametersOid, t.subjectPublicKeyInfoDer, e.signature, n);
286
+ return r.ok ? r.valid ? { ok: !0 } : verifyPkcs7Failure("signature_invalid", "SignedData signature does not verify") : r.code === "verification_error" ? verifyPkcs7Failure("malformed", "SignedData signature verification failed") : verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
287
+ } catch {
288
+ return verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
289
+ }
290
+ }
286
291
  /** Shorthand for constructing a PKCS#7 parse failure result. */
287
- function pkcs7Failure(code, message) {
288
- return failureResult(code, message);
292
+ function pkcs7Failure(e, t) {
293
+ return C(e, t);
289
294
  }
290
295
  /** Shorthand for constructing a PKCS#7 verification failure result. */
291
- function verifyPkcs7Failure(code, message) {
292
- return failureResult(code, message);
296
+ function verifyPkcs7Failure(e, t) {
297
+ return C(e, t);
293
298
  }
294
299
  /** Shorthand for constructing a PKCS#7 certificate bag creation failure result. */
295
- function createCertBagFailure(code, message) {
296
- return failureResult(code, message);
300
+ function createCertBagFailure(e, t) {
301
+ return C(e, t);
297
302
  }
298
303
  /** Shorthand for constructing a PKCS#7 SignedData creation failure result. */
299
- function createPkcs7Failure(code, message) {
300
- return failureResult(code, message);
304
+ function createPkcs7Failure(e, t) {
305
+ return C(e, t);
301
306
  }
302
307
  /** Converts PEM text to an array of DER certificate blobs, or wraps raw DER. */
303
- function normalizeCertificateSource(source) {
304
- if (typeof source === "string") return splitPemBlocksOrThrow(source).filter((block) => block.label === "CERTIFICATE").map((block) => new Uint8Array(block.bytes));
305
- if (source instanceof Uint8Array) return [new Uint8Array(source)];
306
- return [new Uint8Array(source.der)];
308
+ function normalizeCertificateSource(e) {
309
+ return typeof e == "string" ? T(e).filter((e) => e.label === "CERTIFICATE").map((e) => new Uint8Array(e.bytes)) : e instanceof Uint8Array ? [new Uint8Array(e)] : [new Uint8Array(e.der)];
307
310
  }
308
311
  /** Type guard: key algorithm carries an RSA `hash`. */
309
- function signerHasHash(algorithm) {
310
- return "hash" in algorithm;
312
+ function signerHasHash(e) {
313
+ return "hash" in e;
311
314
  }
312
315
  /** Type guard: key algorithm carries an EC `namedCurve`. */
313
- function signerHasNamedCurve(algorithm) {
314
- return "namedCurve" in algorithm;
316
+ function signerHasNamedCurve(e) {
317
+ return "namedCurve" in e;
315
318
  }
316
319
  /**
317
320
  * Resolves the content-digest hash and its OID for a signer key.
@@ -320,47 +323,47 @@ function signerHasNamedCurve(algorithm) {
320
323
  * P-256/RSA-SHA256 → SHA-256, P-384 → SHA-384, P-521 → SHA-512. Ed25519 uses
321
324
  * SHA-512 for the messageDigest attribute, per RFC 8419.
322
325
  */
323
- function contentDigestForPrivateKey(privateKey) {
324
- const algorithm = privateKey.algorithm;
325
- if (algorithm.name === "ECDSA") {
326
- if (!signerHasNamedCurve(algorithm)) return;
327
- switch (algorithm.namedCurve) {
326
+ function contentDigestForPrivateKey(e) {
327
+ let t = e.algorithm;
328
+ if (t.name === "ECDSA") {
329
+ if (!signerHasNamedCurve(t)) return;
330
+ switch (t.namedCurve) {
328
331
  case "P-256": return {
329
332
  hashName: "SHA-256",
330
- digestOid: OIDS.sha256
333
+ digestOid: b.sha256
331
334
  };
332
335
  case "P-384": return {
333
336
  hashName: "SHA-384",
334
- digestOid: OIDS.sha384
337
+ digestOid: b.sha384
335
338
  };
336
339
  case "P-521": return {
337
340
  hashName: "SHA-512",
338
- digestOid: OIDS.sha512
341
+ digestOid: b.sha512
339
342
  };
340
343
  default: return;
341
344
  }
342
345
  }
343
- if (algorithm.name === "RSASSA-PKCS1-v1_5" || algorithm.name === "RSA-PSS") {
344
- if (!signerHasHash(algorithm)) return;
345
- switch (algorithm.hash.name) {
346
+ if (t.name === "RSASSA-PKCS1-v1_5" || t.name === "RSA-PSS") {
347
+ if (!signerHasHash(t)) return;
348
+ switch (t.hash.name) {
346
349
  case "SHA-256": return {
347
350
  hashName: "SHA-256",
348
- digestOid: OIDS.sha256
351
+ digestOid: b.sha256
349
352
  };
350
353
  case "SHA-384": return {
351
354
  hashName: "SHA-384",
352
- digestOid: OIDS.sha384
355
+ digestOid: b.sha384
353
356
  };
354
357
  case "SHA-512": return {
355
358
  hashName: "SHA-512",
356
- digestOid: OIDS.sha512
359
+ digestOid: b.sha512
357
360
  };
358
361
  default: return;
359
362
  }
360
363
  }
361
- if (algorithm.name === "Ed25519") return {
364
+ if (t.name === "Ed25519") return {
362
365
  hashName: "SHA-512",
363
- digestOid: OIDS.sha512
366
+ digestOid: b.sha512
364
367
  };
365
368
  }
366
369
  /**
@@ -369,285 +372,240 @@ function contentDigestForPrivateKey(privateKey) {
369
372
  * Section 5.4; `implicitForEmit` (IMPLICIT [0], tag 0xa0) is what goes in the
370
373
  * SignerInfo. The two differ only in the leading tag byte.
371
374
  */
372
- function buildSignedAttributes(contentTypeOid, messageDigest) {
373
- const setForSigning = setOf([sequence([objectIdentifier(OIDS.cmsContentType), setOf([objectIdentifier(contentTypeOid)])]), sequence([objectIdentifier(OIDS.cmsMessageDigest), setOf([octetString(messageDigest)])])]);
374
- const implicitForEmit = new Uint8Array(setForSigning);
375
- implicitForEmit[0] = 160;
376
- return {
377
- setForSigning,
378
- implicitForEmit
375
+ function buildSignedAttributes(e, t) {
376
+ let n = d([u([a(b.cmsContentType), d([a(e)])]), u([a(b.cmsMessageDigest), d([o(t)])])]), r = new Uint8Array(n);
377
+ return r[0] = 160, {
378
+ setForSigning: n,
379
+ implicitForEmit: r
379
380
  };
380
381
  }
381
382
  /** Parses the IMPLICIT [0] certificate set from a SignedData structure. */
382
- function parseCertificateSet(source, certificates) {
383
- if (certificates === void 0 || certificates.tag !== 160) return [];
384
- const parsed = [];
385
- let offset = certificates.start;
386
- while (offset < certificates.end) {
387
- const element = readElement(source, offset);
388
- parsed.push(parseCertificateDerOrThrow(source.slice(offset, element.end)));
389
- offset = element.end;
383
+ function parseCertificateSet(e, t) {
384
+ if (t === void 0 || t.tag !== 160) return [];
385
+ let n = [], r = t.start;
386
+ for (; r < t.end;) {
387
+ let t = s(e, r);
388
+ n.push(k(e.slice(r, t.end))), r = t.end;
390
389
  }
391
- return parsed;
390
+ return n;
392
391
  }
393
392
  /** Extracts the list of digest algorithm OIDs from the digestAlgorithms SET. */
394
- function parseDigestAlgorithms(source, element) {
395
- const digests = [];
396
- if (element.tag !== 49) throw new Error("digestAlgorithms must use SET");
397
- for (const child of childrenOf(source, element)) {
398
- if (child.tag !== 48) throw new Error("digestAlgorithm must use AlgorithmIdentifier SEQUENCE");
399
- const parts = readSequenceChildren(source.slice(child.start - child.headerLength, child.end));
400
- const oid = parts[0];
401
- if (oid === void 0 || parts.length < 1 || parts.length > 2 || oid.tag !== 6) throw new Error("Malformed digest AlgorithmIdentifier");
402
- digests.push(decodeObjectIdentifier(oid.value));
393
+ function parseDigestAlgorithms(e, t) {
394
+ let n = [];
395
+ if (t.tag !== 49) throw Error("digestAlgorithms must use SET");
396
+ for (let r of f(e, t)) {
397
+ if (r.tag !== 48) throw Error("digestAlgorithm must use AlgorithmIdentifier SEQUENCE");
398
+ let t = l(e.slice(r.start - r.headerLength, r.end)), i = t[0];
399
+ if (i === void 0 || t.length < 1 || t.length > 2 || i.tag !== 6) throw Error("Malformed digest AlgorithmIdentifier");
400
+ n.push(m(i.value));
403
401
  }
404
- return digests;
402
+ return n;
405
403
  }
406
404
  /** Decodes the signerInfos SET OF from a SignedData structure. */
407
- function parseSignerInfos(source, element) {
408
- const signers = [];
409
- for (const signerInfo of childrenOf(source, element)) {
410
- const signerDer = source.slice(signerInfo.start - signerInfo.headerLength, signerInfo.end);
411
- const parts = readSequenceChildren(signerDer);
412
- const version = parts[0];
413
- const sid = parts[1];
414
- const digestAlgorithm = parts[2];
415
- let index = 3;
416
- const signedAttrsElement = parts[index]?.tag === 160 ? parts[index] : void 0;
417
- if (signedAttrsElement !== void 0) index += 1;
418
- const signatureAlgorithm = parts[index];
419
- const signature = parts[index + 1];
420
- const unauthenticatedAttributes = parts[index + 2];
421
- if (version === void 0 || sid === void 0 || digestAlgorithm === void 0 || signatureAlgorithm === void 0 || signature === void 0 || signature.tag !== 4 || parts.length > index + 3 || unauthenticatedAttributes !== void 0 && unauthenticatedAttributes.tag !== 161) throw new Error("Malformed SignerInfo");
422
- const digestAlgorithmOid = decodeObjectIdentifier(requireElement(readSequenceChildren(signerDer.slice(digestAlgorithm.start - digestAlgorithm.headerLength, digestAlgorithm.end))[0], "digest algorithm OID").value);
423
- const signatureAlgorithmDer = signerDer.slice(signatureAlgorithm.start - signatureAlgorithm.headerLength, signatureAlgorithm.end);
424
- const signatureAlgorithmChildren = readSequenceChildren(signatureAlgorithmDer);
425
- const signatureAlgorithmOid = decodeObjectIdentifier(requireElement(signatureAlgorithmChildren[0], "signature algorithm OID").value);
426
- const signatureAlgorithmParams = signatureAlgorithmChildren[1];
427
- const parsedSid = parseSignerIdentifier(signerDer.slice(sid.start - sid.headerLength, sid.end));
428
- signers.push({
429
- version: decodeIntegerNumber(version.value),
430
- ...parsedSid.issuer === void 0 ? {} : { issuer: parsedSid.issuer },
431
- ...parsedSid.serialNumberHex === void 0 ? {} : { serialNumberHex: parsedSid.serialNumberHex },
432
- ...parsedSid.subjectKeyIdentifier === void 0 ? {} : { subjectKeyIdentifier: parsedSid.subjectKeyIdentifier },
433
- digestAlgorithmOid,
434
- digestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),
435
- signatureAlgorithmOid,
436
- signatureAlgorithmName: describeSignatureAlgorithm(signatureAlgorithmOid, signatureAlgorithmParams === void 0 ? void 0 : new Uint8Array(signatureAlgorithmDer.slice(signatureAlgorithmParams.start - signatureAlgorithmParams.headerLength, signatureAlgorithmParams.end))),
437
- ...signatureAlgorithmParams === void 0 ? {} : { signatureAlgorithmParametersDer: new Uint8Array(signatureAlgorithmDer.slice(signatureAlgorithmParams.start - signatureAlgorithmParams.headerLength, signatureAlgorithmParams.end)) },
438
- signatureHex: toHex(signature.value),
439
- signature: new Uint8Array(signature.value),
440
- ...signedAttrsElement === void 0 ? { hasSignedAttrs: false } : {
441
- hasSignedAttrs: true,
442
- signedAttrsDer: new Uint8Array(signerDer.slice(signedAttrsElement.start - signedAttrsElement.headerLength, signedAttrsElement.end))
443
- }
444
- });
445
- }
446
- return signers;
405
+ function parseSignerInfos(e, t) {
406
+ return f(e, t).map((t) => parseSignerInfo(e, t));
407
+ }
408
+ function parseSignerInfo(e, t) {
409
+ let n = e.slice(t.start - t.headerLength, t.end), r = l(n), i = r[0], a = r[1], o = r[2], s = 3, c = r[s]?.tag === 160 ? r[s] : void 0;
410
+ c !== void 0 && (s += 1);
411
+ let u = r[s], d = r[s + 1], f = r[s + 2];
412
+ if (i === void 0 || a === void 0 || o === void 0 || u === void 0 || d === void 0 || d.tag !== 4 || r.length > s + 3 || f !== void 0 && f.tag !== 161) throw Error("Malformed SignerInfo");
413
+ let h = parsePkcs7AlgorithmOid(n, o, "digest algorithm OID"), g = n.slice(u.start - u.headerLength, u.end), v = l(g), b = m(_(v[0], "signature algorithm OID").value), x = v[1], S = parseSignerIdentifier(n.slice(a.start - a.headerLength, a.end));
414
+ return {
415
+ version: p(i.value),
416
+ ...S.issuer === void 0 ? {} : { issuer: S.issuer },
417
+ ...S.serialNumberHex === void 0 ? {} : { serialNumberHex: S.serialNumberHex },
418
+ ...S.subjectKeyIdentifier === void 0 ? {} : { subjectKeyIdentifier: S.subjectKeyIdentifier },
419
+ digestAlgorithmOid: h,
420
+ digestAlgorithmName: E(h),
421
+ signatureAlgorithmOid: b,
422
+ signatureAlgorithmName: D(b, x === void 0 ? void 0 : new Uint8Array(g.slice(x.start - x.headerLength, x.end))),
423
+ ...x === void 0 ? {} : { signatureAlgorithmParametersDer: new Uint8Array(g.slice(x.start - x.headerLength, x.end)) },
424
+ signatureHex: y(d.value),
425
+ signature: new Uint8Array(d.value),
426
+ ...c === void 0 ? { hasSignedAttrs: !1 } : {
427
+ hasSignedAttrs: !0,
428
+ signedAttrsDer: new Uint8Array(n.slice(c.start - c.headerLength, c.end))
429
+ }
430
+ };
431
+ }
432
+ function parsePkcs7AlgorithmOid(e, t, n) {
433
+ return m(_(l(e.slice(t.start - t.headerLength, t.end))[0], n).value);
447
434
  }
448
435
  /** Unwraps the OCTET STRING inside the IMPLICIT [0] encapsulated content. */
449
- function extractEncapsulatedContent(encapDer, element) {
450
- if (element.tag !== 160) throw new Error("Unexpected encapsulated content tag");
451
- const inner = readElement(encapDer, element.start);
452
- if (inner.tag !== 4) throw new Error("Expected encapsulated OCTET STRING");
453
- return inner.value;
436
+ function extractEncapsulatedContent(e, t) {
437
+ if (t.tag !== 160) throw Error("Unexpected encapsulated content tag");
438
+ let n = s(e, t.start);
439
+ if (n.tag !== 4) throw Error("Expected encapsulated OCTET STRING");
440
+ return n.value;
454
441
  }
455
442
  /** Extracts issuer Name and serial number from an issuerAndSerialNumber SEQUENCE, or subjectKeyIdentifier from [0] IMPLICIT. */
456
- function parseSignerIdentifier(der) {
457
- const element = readRootElement(der, { maxDepth: 64 });
458
- if (element.tag === 128) {
459
- if (element.value.length === 0) throw new Error("SignerIdentifier subjectKeyIdentifier must not be empty");
460
- return { subjectKeyIdentifier: toHex(element.value) };
443
+ function parseSignerIdentifier(e) {
444
+ let t = c(e, { maxDepth: 64 });
445
+ if (t.tag === 128) {
446
+ if (t.value.length === 0) throw Error("SignerIdentifier subjectKeyIdentifier must not be empty");
447
+ return { subjectKeyIdentifier: y(t.value) };
461
448
  }
462
- if (element.tag === 48) {
463
- const top = readSequenceChildren(der);
464
- const issuerElement = top[0];
465
- const serial = top[1];
466
- if (issuerElement === void 0 || serial === void 0 || top.length !== 2) throw new Error("SignerIdentifier issuerAndSerialNumber is malformed");
467
- if (issuerElement.tag !== 48) throw new Error("SignerIdentifier issuer must use Name SEQUENCE");
468
- if (serial.tag !== 2) throw new Error("SignerIdentifier serialNumber must use INTEGER");
469
- assertImplicitSerialNumberEncoding(serial.value, "SignerIdentifier serialNumber");
470
- return {
471
- issuer: parseSignerIssuerName(der, issuerElement),
472
- serialNumberHex: toHex(serial.value)
449
+ if (t.tag === 48) {
450
+ let t = l(e), n = t[0], r = t[1];
451
+ if (n === void 0 || r === void 0 || t.length !== 2) throw Error("SignerIdentifier issuerAndSerialNumber is malformed");
452
+ if (n.tag !== 48) throw Error("SignerIdentifier issuer must use Name SEQUENCE");
453
+ if (r.tag !== 2) throw Error("SignerIdentifier serialNumber must use INTEGER");
454
+ return assertImplicitSerialNumberEncoding(r.value, "SignerIdentifier serialNumber"), {
455
+ issuer: parseSignerIssuerName(e, n),
456
+ serialNumberHex: y(r.value)
473
457
  };
474
458
  }
475
- throw new Error(`Unsupported SignerIdentifier tag: ${String(element.tag)}`);
459
+ throw Error(`Unsupported SignerIdentifier tag: ${String(t.tag)}`);
476
460
  }
477
- const textDecoder = new TextDecoder();
461
+ const F = new TextDecoder();
478
462
  /** Parses a Name SEQUENCE element from a PKCS#7 signer identifier into a {@linkcode ParsedName}. */
479
- function parseSignerIssuerName(source, element) {
480
- const derHex = toHex(source.slice(element.start - element.headerLength, element.end));
481
- const rdns = [];
482
- const allAttributes = [];
483
- const values = {};
484
- for (const setElement of childrenOf(source, element)) {
485
- const rdnAttributes = [];
486
- const rdnValues = {};
487
- for (const attrSequence of childrenOf(source, setElement)) {
488
- const parts = childrenOf(source, attrSequence);
489
- const oidElement = requireElement(parts[0], "signer issuer attribute OID");
490
- const valueElement = requireElement(parts[1], "signer issuer attribute value");
491
- const oid = decodeObjectIdentifier(oidElement.value);
492
- let fieldValue;
463
+ function parseSignerIssuerName(e, t) {
464
+ let n = y(e.slice(t.start - t.headerLength, t.end)), r = [], i = [], a = {};
465
+ for (let n of f(e, t)) {
466
+ let t = [], o = {};
467
+ for (let r of f(e, n)) {
468
+ let n = f(e, r), s = _(n[0], "signer issuer attribute OID"), c = _(n[1], "signer issuer attribute value"), l = m(s.value), u;
493
469
  try {
494
- fieldValue = decodeString(valueElement.tag, valueElement.value);
470
+ u = h(c.tag, c.value);
495
471
  } catch {
496
- fieldValue = textDecoder.decode(valueElement.value);
472
+ u = F.decode(c.value);
497
473
  }
498
- const fieldKey = nameFieldKeyFromOid(oid);
499
- const attribute = fieldKey !== void 0 ? {
500
- oid,
501
- key: fieldKey,
502
- valueTag: valueElement.tag,
503
- value: fieldValue
474
+ let d = O(l), p = d === void 0 ? {
475
+ oid: l,
476
+ valueTag: c.tag,
477
+ value: u
504
478
  } : {
505
- oid,
506
- valueTag: valueElement.tag,
507
- value: fieldValue
479
+ oid: l,
480
+ key: d,
481
+ valueTag: c.tag,
482
+ value: u
508
483
  };
509
- rdnAttributes.push(attribute);
510
- allAttributes.push(attribute);
511
- if (fieldKey !== void 0) {
512
- if (rdnValues[fieldKey] === void 0) rdnValues[fieldKey] = fieldValue;
513
- if (values[fieldKey] === void 0) values[fieldKey] = fieldValue;
514
- }
484
+ t.push(p), i.push(p), d !== void 0 && (o[d] === void 0 && (o[d] = u), a[d] === void 0 && (a[d] = u));
515
485
  }
516
- rdns.push({
517
- derHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),
518
- attributes: rdnAttributes,
519
- values: rdnValues
486
+ r.push({
487
+ derHex: y(e.slice(n.start - n.headerLength, n.end)),
488
+ attributes: t,
489
+ values: o
520
490
  });
521
491
  }
522
492
  return {
523
- derHex,
524
- rdns,
525
- attributes: allAttributes,
526
- values
493
+ derHex: n,
494
+ rdns: r,
495
+ attributes: i,
496
+ values: a
527
497
  };
528
498
  }
529
499
  /** Returns the nth child element inside a constructed ASN.1 element, or throws. */
530
- function childAt(source, parent, index, label) {
531
- let offset = parent.start;
532
- let currentIndex = 0;
533
- while (offset < parent.end) {
534
- const child = readElement(source, offset);
535
- if (currentIndex === index) return child;
536
- offset = child.end;
537
- currentIndex += 1;
500
+ function childAt(e, t, n, r) {
501
+ let i = t.start, a = 0;
502
+ for (; i < t.end;) {
503
+ let t = s(e, i);
504
+ if (a === n) return t;
505
+ i = t.end, a += 1;
538
506
  }
539
- throw new Error(`Missing ${label}`);
507
+ throw Error(`Missing ${r}`);
540
508
  }
541
509
  /** Maps a digest algorithm OID to the WebCrypto hash name. */
542
- function digestAlgorithmHash(digestAlgorithmOid) {
543
- switch (digestAlgorithmOid) {
544
- case OIDS.sha256: return "SHA-256";
545
- case OIDS.sha384: return "SHA-384";
546
- case OIDS.sha512: return "SHA-512";
547
- default: throw new Error(`Unsupported digest algorithm OID: ${digestAlgorithmOid}`);
510
+ function digestAlgorithmHash(e) {
511
+ switch (e) {
512
+ case b.sha256: return "SHA-256";
513
+ case b.sha384: return "SHA-384";
514
+ case b.sha512: return "SHA-512";
515
+ default: throw Error(`Unsupported digest algorithm OID: ${e}`);
548
516
  }
549
517
  }
550
518
  /** Parses required signed attributes and enforces uniqueness + exact-one-value shape. */
551
- function parseSignedAttributeRequirements(signedAttrsDer) {
552
- const outer = readElement(signedAttrsDer);
553
- let messageDigest;
554
- let contentTypeOid;
555
- for (const attr of childrenOf(signedAttrsDer, outer)) {
556
- const attrDer = signedAttrsDer.slice(attr.start - attr.headerLength, attr.end);
557
- const parts = readSequenceChildren(attrDer);
558
- const oid = parts[0];
559
- const values = parts[1];
560
- if (oid === void 0 || values === void 0 || parts.length !== 2 || values.tag !== 49) throw new Error("Malformed signedAttrs attribute");
561
- const attrOid = decodeObjectIdentifier(oid.value);
562
- const valueElements = childrenOf(attrDer, values);
563
- if (attrOid === OIDS.cmsMessageDigest) {
564
- if (messageDigest !== void 0 || valueElements.length !== 1) throw new Error("messageDigest attribute must appear exactly once with one value");
565
- const digestElement = valueElements[0];
566
- if (digestElement === void 0 || digestElement.tag !== 4) throw new Error("messageDigest attribute value must use OCTET STRING");
567
- messageDigest = digestElement.value;
568
- continue;
569
- }
570
- if (attrOid === OIDS.cmsContentType) {
571
- if (contentTypeOid !== void 0 || valueElements.length !== 1) throw new Error("contentType attribute must appear exactly once with one value");
572
- const contentType = valueElements[0];
573
- if (contentType === void 0 || contentType.tag !== 6) throw new Error("contentType attribute value must use OBJECT IDENTIFIER");
574
- contentTypeOid = decodeObjectIdentifier(contentType.value);
575
- }
576
- }
577
- if (messageDigest === void 0) throw new Error("Missing messageDigest attribute in signedAttrs");
578
- if (contentTypeOid === void 0) throw new Error("Missing contentType attribute in signedAttrs");
519
+ function parseSignedAttributeRequirements(e) {
520
+ let t = s(e), n = {};
521
+ for (let r of f(e, t)) parseSignedAttributeRequirement(e, r, n);
522
+ if (n.messageDigest === void 0) throw Error("Missing messageDigest attribute in signedAttrs");
523
+ if (n.contentTypeOid === void 0) throw Error("Missing contentType attribute in signedAttrs");
579
524
  return {
580
- messageDigest,
581
- contentTypeOid
525
+ messageDigest: n.messageDigest,
526
+ contentTypeOid: n.contentTypeOid
582
527
  };
583
528
  }
529
+ function parseSignedAttributeRequirement(e, t, n) {
530
+ let r = e.slice(t.start - t.headerLength, t.end), i = l(r), a = i[0], o = i[1];
531
+ if (a === void 0 || o === void 0 || i.length !== 2 || o.tag !== 49) throw Error("Malformed signedAttrs attribute");
532
+ let s = m(a.value), c = f(r, o);
533
+ s === b.cmsMessageDigest && (n.messageDigest = parseUniqueSignedAttributeOctetString(n.messageDigest, c, "messageDigest")), s === b.cmsContentType && (n.contentTypeOid = parseUniqueSignedAttributeOid(n.contentTypeOid, c, "contentType"));
534
+ }
535
+ function parseUniqueSignedAttributeOctetString(e, t, n) {
536
+ if (e !== void 0 || t.length !== 1) throw Error(`${n} attribute must appear exactly once with one value`);
537
+ let r = _(t[0], `${n} attribute value`);
538
+ if (r.tag !== 4) throw Error(`${n} attribute value must use OCTET STRING`);
539
+ return r.value;
540
+ }
541
+ function parseUniqueSignedAttributeOid(e, t, n) {
542
+ if (e !== void 0 || t.length !== 1) throw Error(`${n} attribute must appear exactly once with one value`);
543
+ let r = _(t[0], `${n} attribute value`);
544
+ if (r.tag !== 6) throw Error(`${n} attribute value must use OBJECT IDENTIFIER`);
545
+ return m(r.value);
546
+ }
584
547
  /** Replaces the IMPLICIT [0] tag (0xa0) with SET OF (0x31) per RFC 5652 Section 5.4. */
585
- function retagSignedAttrsAsSet(signedAttrsDer) {
586
- const copy = new Uint8Array(signedAttrsDer);
587
- copy[0] = 49;
588
- return copy;
548
+ function retagSignedAttrsAsSet(e) {
549
+ let t = new Uint8Array(e);
550
+ return t[0] = 49, t;
589
551
  }
590
552
  /** Constant-time byte comparison to avoid timing side-channels in digest checks. */
591
- function constantTimeEqual(a, b) {
592
- if (a.length !== b.length) return false;
593
- let diff = 0;
594
- for (let index = 0; index < a.length; index += 1) diff |= (a[index] ?? 0) ^ (b[index] ?? 0);
595
- return diff === 0;
553
+ function constantTimeEqual(e, t) {
554
+ if (e.length !== t.length) return !1;
555
+ let n = 0;
556
+ for (let r = 0; r < e.length; r += 1) n |= (e[r] ?? 0) ^ (t[r] ?? 0);
557
+ return n === 0;
596
558
  }
597
559
  /** Verifies a signed-attributes flow: digest match + signature over re-tagged attrs. */
598
- async function verifySignedAttrs(signerInfo, signer, encapsulatedContent, encapsulatedContentTypeOid) {
599
- if (!signerInfo.hasSignedAttrs) return verifyPkcs7Failure("malformed", "Missing signedAttrs DER");
600
- let signedAttributes;
560
+ async function verifySignedAttrs(e, t, n, r) {
561
+ if (!e.hasSignedAttrs) return verifyPkcs7Failure("malformed", "Missing signedAttrs DER");
562
+ let i;
601
563
  try {
602
- assertImplicitSignedAttrsDer(signerInfo.signedAttrsDer);
603
- signedAttributes = parseSignedAttributeRequirements(signerInfo.signedAttrsDer);
564
+ assertImplicitSignedAttrsDer(e.signedAttrsDer), i = parseSignedAttributeRequirements(e.signedAttrsDer);
604
565
  } catch {
605
566
  return verifyPkcs7Failure("malformed", "Malformed signedAttrs in SignedData");
606
567
  }
607
- if (signedAttributes.contentTypeOid !== encapsulatedContentTypeOid) return verifyPkcs7Failure("malformed", "SignedData contentType attribute does not match");
608
- let actualDigest;
568
+ if (i.contentTypeOid !== r) return verifyPkcs7Failure("malformed", "SignedData contentType attribute does not match");
569
+ let a;
609
570
  try {
610
- const hash = digestAlgorithmHash(signerInfo.digestAlgorithmOid);
611
- actualDigest = new Uint8Array(await getCrypto().subtle.digest(hash, toArrayBuffer(encapsulatedContent)));
571
+ let t = digestAlgorithmHash(e.digestAlgorithmOid);
572
+ a = new Uint8Array(await x().subtle.digest(t, v(n)));
612
573
  } catch {
613
574
  return verifyPkcs7Failure("malformed", "Unsupported digest algorithm in SignedData");
614
575
  }
615
- if (!constantTimeEqual(actualDigest, signedAttributes.messageDigest)) return verifyPkcs7Failure("message_digest_mismatch", "Content digest does not match messageDigest attribute");
616
- let signedData;
576
+ if (!constantTimeEqual(a, i.messageDigest)) return verifyPkcs7Failure("message_digest_mismatch", "Content digest does not match messageDigest attribute");
577
+ let o;
617
578
  try {
618
- signedData = retagSignedAttrsAsSet(signerInfo.signedAttrsDer);
579
+ o = retagSignedAttrsAsSet(e.signedAttrsDer);
619
580
  } catch {
620
581
  return verifyPkcs7Failure("malformed", "Malformed signedAttrs in SignedData");
621
582
  }
622
- let verified;
583
+ let s;
623
584
  try {
624
- const verificationResult = await verifySignedDataDetailed(signerInfo.signatureAlgorithmOid, signerInfo.signatureAlgorithmParametersDer, signer.publicKeyAlgorithmOid, signer.publicKeyParametersOid, signer.subjectPublicKeyInfoDer, signerInfo.signature, signedData);
625
- if (!verificationResult.ok) {
626
- if (verificationResult.code === "verification_error") return verifyPkcs7Failure("malformed", "SignedData signature verification failed");
627
- return verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
628
- }
629
- verified = verificationResult.valid;
585
+ let n = await A(e.signatureAlgorithmOid, e.signatureAlgorithmParametersDer, t.publicKeyAlgorithmOid, t.publicKeyParametersOid, t.subjectPublicKeyInfoDer, e.signature, o);
586
+ if (!n.ok) return n.code === "verification_error" ? verifyPkcs7Failure("malformed", "SignedData signature verification failed") : verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
587
+ s = n.valid;
630
588
  } catch {
631
589
  return verifyPkcs7Failure("malformed", "Unsupported signature algorithm in SignedData");
632
590
  }
633
- if (!verified) return verifyPkcs7Failure("signature_invalid", "SignedData signature over signedAttrs does not verify");
634
- return { ok: true };
591
+ return s ? { ok: !0 } : verifyPkcs7Failure("signature_invalid", "SignedData signature over signedAttrs does not verify");
635
592
  }
636
- function signerIdentifierMatches(certificate, signerInfo) {
637
- if (signerInfo.issuer !== void 0 || signerInfo.serialNumberHex !== void 0) return signerInfo.issuer !== void 0 && signerInfo.serialNumberHex !== void 0 && certificate.serialNumberHex === signerInfo.serialNumberHex && compareDistinguishedNames(certificate.issuer, signerInfo.issuer);
638
- return signerInfo.subjectKeyIdentifier !== void 0 && certificate.subjectKeyIdentifier === signerInfo.subjectKeyIdentifier;
593
+ function signerIdentifierMatches(e, t) {
594
+ return t.issuer !== void 0 || t.serialNumberHex !== void 0 ? t.issuer !== void 0 && t.serialNumberHex !== void 0 && e.serialNumberHex === t.serialNumberHex && P(e.issuer, t.issuer) : t.subjectKeyIdentifier !== void 0 && e.subjectKeyIdentifier === t.subjectKeyIdentifier;
639
595
  }
640
- function assertImplicitSignedAttrsDer(signedAttrsDer) {
641
- if (readElement(signedAttrsDer).tag !== 160) throw new Error("signedAttrs must use IMPLICIT [0] tag");
596
+ function assertImplicitSignedAttrsDer(e) {
597
+ if (s(e).tag !== 160) throw Error("signedAttrs must use IMPLICIT [0] tag");
642
598
  }
643
- function hasReparseablePkcs7SignedData(value) {
644
- return "der" in value && value.der instanceof Uint8Array;
599
+ function hasReparseablePkcs7SignedData(e) {
600
+ return "der" in e && e.der instanceof Uint8Array;
645
601
  }
646
- function assertImplicitSerialNumberEncoding(bytes, label) {
647
- const first = bytes[0];
648
- if (first === void 0) throw new Error(`${label} must not be empty`);
649
- if ((first & 128) !== 0) throw new Error(`${label} must be non-negative`);
650
- if (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 128) === 0) throw new Error(`${label} must use minimal encoding`);
602
+ function assertImplicitSerialNumberEncoding(e, t) {
603
+ let n = e[0];
604
+ if (n === void 0) throw Error(`${t} must not be empty`);
605
+ if (n & 128) throw Error(`${t} must be non-negative`);
606
+ if (e.length > 1 && n === 0 && !((e[1] ?? 0) & 128)) throw Error(`${t} must use minimal encoding`);
651
607
  }
652
608
  //#endregion
653
609
  export { createPkcs7CertBag, createPkcs7SignedData, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData };
610
+
611
+ //# sourceMappingURL=pkcs7.js.map