micro509 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -30
- package/dist/crypto/crypto.d.ts +73 -0
- package/dist/crypto/crypto.js +74 -0
- package/dist/crypto/crypto.js.map +1 -0
- package/dist/crypto.d.ts +4 -0
- package/dist/crypto.js +2 -0
- package/dist/der/der.d.ts +1 -1
- package/dist/index.d.ts +13 -9
- package/dist/index.js +17 -15
- package/dist/internal/asn1/asn1.js +21 -10
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +4 -2
- package/dist/internal/asn1/der.js +18 -5
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +7 -1
- package/dist/internal/crypto/algorithm-names.js +4 -0
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +38 -0
- package/dist/internal/crypto/pbes2.js +9 -10
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js +2 -0
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +31 -0
- package/dist/internal/crypto/sig-verify.js +10 -8
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/shared/base64.js +7 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +16 -0
- package/dist/internal/shared/dn.js +13 -6
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +69 -0
- package/dist/internal/shared/ip.js +18 -1
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +7 -0
- package/dist/internal/verify/verify-path.js +36 -36
- package/dist/internal/x509/directory-name.js +24 -0
- package/dist/internal/x509/directory-name.js.map +1 -0
- package/dist/internal/x509/extension-bits.js +13 -10
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +6 -0
- package/dist/internal/x509/extension-errors.js +20 -0
- package/dist/internal/x509/extension-errors.js.map +1 -0
- package/dist/internal/x509/extension-registry.js +113 -55
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-tags.js +28 -0
- package/dist/internal/x509/general-name-tags.js.map +1 -0
- package/dist/internal/x509/general-name.js +97 -0
- package/dist/internal/x509/general-name.js.map +1 -0
- package/dist/internal/x509/name-fields.js +20 -10
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/keys/keys.d.ts +16 -2
- package/dist/keys/keys.js +311 -170
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +3 -2
- package/dist/keys.js +3 -2
- package/dist/pem/pem.d.ts +3 -2
- package/dist/pem/pem.js +112 -30
- package/dist/pem/pem.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.js +3 -3
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +85 -21
- package/dist/pkcs/pkcs7.js +261 -186
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +2 -2
- package/dist/result/result.d.ts +18 -10
- package/dist/result/result.js +20 -12
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +2 -2
- package/dist/result.js +2 -2
- package/dist/revocation/chain.js +77 -81
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +13 -2
- package/dist/revocation/crl.js +415 -236
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +58 -17
- package/dist/revocation/ocsp.js +185 -173
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +4 -4
- package/dist/revocation/revocation.js +48 -30
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +4 -4
- package/dist/revocation.js +5 -5
- package/dist/verify/identity.d.ts +2 -1
- package/dist/verify/identity.js +2 -1
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/policy.d.ts +6 -1
- package/dist/verify/verify.d.ts +4 -2
- package/dist/verify/verify.js +32 -14
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -1
- package/dist/verify.js +4 -3
- package/dist/x509/certificate.d.ts +36 -13
- package/dist/x509/certificate.js +36 -19
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +6 -3
- package/dist/x509/extensions.d.ts +58 -21
- package/dist/x509/extensions.js +384 -117
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/name-text.js +2 -0
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +8 -5
- package/dist/x509/name.js +17 -12
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +104 -18
- package/dist/x509/parse.js +127 -163
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +8 -5
- package/dist/x509.js +10 -8
- package/package.json +28 -20
package/dist/pem/pem.js
CHANGED
|
@@ -9,6 +9,7 @@ import { failureResult as n, rethrowIfInvariant as r, successResult as i } from
|
|
|
9
9
|
*
|
|
10
10
|
* @module
|
|
11
11
|
*/
|
|
12
|
+
const a = /^(?:[!-,.-~](?:[- ]?[!-,.-~])*)?$/;
|
|
12
13
|
/**
|
|
13
14
|
* Wraps DER bytes in a PEM envelope with 64-character base64 lines.
|
|
14
15
|
*
|
|
@@ -16,23 +17,24 @@ import { failureResult as n, rethrowIfInvariant as r, successResult as i } from
|
|
|
16
17
|
* @param der Raw DER-encoded content.
|
|
17
18
|
*/
|
|
18
19
|
function pemEncode(e, n) {
|
|
19
|
-
|
|
20
|
+
if (!isPemLabel(e)) throw Error("Invalid PEM label");
|
|
21
|
+
return `-----BEGIN ${e}-----\n${(t(n).match(/.{1,64}/g) ?? []).join("\n")}\n-----END ${e}-----\n`;
|
|
20
22
|
}
|
|
21
23
|
/**
|
|
22
24
|
* Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the
|
|
23
|
-
* DER content from a PEM string.
|
|
24
|
-
* match `label`.
|
|
25
|
+
* DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.
|
|
26
|
+
* Throws if the `BEGIN`/`END` markers don't match `label`.
|
|
25
27
|
*
|
|
26
28
|
* @param label Expected PEM type label.
|
|
27
29
|
* @param pem PEM-encoded text (may contain `\r`).
|
|
28
30
|
*/
|
|
29
31
|
function pemDecodeOrThrow(t, n) {
|
|
30
|
-
let r = n.replace(/\r
|
|
31
|
-
if (
|
|
32
|
-
let
|
|
33
|
-
if (
|
|
32
|
+
let r = trimPemDocument(n.replace(/\r\n?/g, "\n")).split("\n"), i = findPreEncapsulationBoundary(r);
|
|
33
|
+
if (i === void 0 || parsePemBoundaryLine(r[i] ?? "", "BEGIN") !== t || parsePemBoundaryLine(r[r.length - 1] ?? "", "END") !== t || r.length - i < 3) throw Error(`Invalid PEM for ${t}`);
|
|
34
|
+
let a = normalizePemBodyLines(r.slice(i + 1, -1));
|
|
35
|
+
if (a === void 0) throw Error(`Invalid PEM for ${t}`);
|
|
34
36
|
try {
|
|
35
|
-
return e(
|
|
37
|
+
return e(a.join(""));
|
|
36
38
|
} catch {
|
|
37
39
|
throw Error(`Invalid PEM for ${t}`);
|
|
38
40
|
}
|
|
@@ -43,30 +45,32 @@ function pemDecodeOrThrow(t, n) {
|
|
|
43
45
|
* and ignores non-PEM text between blocks.
|
|
44
46
|
*/
|
|
45
47
|
function splitPemBlocksOrThrow(e) {
|
|
46
|
-
let t = e.replace(/\r
|
|
48
|
+
let t = e.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n"), n = [], r, i = 0;
|
|
47
49
|
for (; i < t.length;) {
|
|
48
|
-
let e = t.indexOf("
|
|
50
|
+
let e = t.indexOf("\n", i), a = e === -1 ? t.length : e, o = e === -1 ? t.length : e + 1, s = t.slice(i, a), c = s.replace(/^[ \t]+/, ""), l = parsePemBoundaryLine(s, "BEGIN"), u = parsePemBoundaryLine(s, "END");
|
|
51
|
+
if (l !== void 0) {
|
|
52
|
+
if (r !== void 0) throw Error("Malformed PEM block");
|
|
53
|
+
r = {
|
|
54
|
+
label: l,
|
|
55
|
+
start: i + s.length - c.length
|
|
56
|
+
};
|
|
57
|
+
} else if (u !== void 0) n.push(closePemBlock(t, r, u, o)), r = void 0;
|
|
58
|
+
else if (looksLikePemBoundary(s)) throw Error("Malformed PEM block");
|
|
49
59
|
if (e === -1) break;
|
|
50
|
-
|
|
51
|
-
if (o === -1) break;
|
|
52
|
-
let s = t.slice(a, o), c = o + 5;
|
|
53
|
-
if (s.length === 0 || s.includes("-") || s.includes("\n") || t[c] !== "\n") {
|
|
54
|
-
i = a;
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
let l = c + 1, u = `\n-----END ${s}-----`, d = t.indexOf(u, l);
|
|
58
|
-
if (d === -1) break;
|
|
59
|
-
let f = d + u.length, p = t.slice(e, f);
|
|
60
|
-
if (containsPemMarker(t.slice(r, e))) throw Error("Malformed PEM block");
|
|
61
|
-
n.push({
|
|
62
|
-
label: s,
|
|
63
|
-
bytes: pemDecodeOrThrow(s, p),
|
|
64
|
-
pem: p
|
|
65
|
-
}), r = f, i = f;
|
|
60
|
+
i = o;
|
|
66
61
|
}
|
|
67
|
-
if (
|
|
62
|
+
if (r !== void 0) throw Error("Malformed PEM block");
|
|
68
63
|
return n;
|
|
69
64
|
}
|
|
65
|
+
function closePemBlock(e, t, n, r) {
|
|
66
|
+
if (t === void 0 || t.label !== n) throw Error("Malformed PEM block");
|
|
67
|
+
let i = e.slice(t.start, r);
|
|
68
|
+
return {
|
|
69
|
+
label: t.label,
|
|
70
|
+
bytes: pemDecodeOrThrow(t.label, i),
|
|
71
|
+
pem: i
|
|
72
|
+
};
|
|
73
|
+
}
|
|
70
74
|
/**
|
|
71
75
|
* Groups PEM blocks by label into well-known PKI categories
|
|
72
76
|
* (certificates, CSRs, private keys, public keys, and everything else).
|
|
@@ -103,11 +107,89 @@ function normalizePemBodyLines(e) {
|
|
|
103
107
|
let t = e.map((e) => e.replace(/[ \t]/g, "")).filter((e) => e !== "");
|
|
104
108
|
return t.length === 0 ? [""] : t.every((e) => /^[A-Za-z0-9+/=]+$/.test(e)) ? t : void 0;
|
|
105
109
|
}
|
|
106
|
-
function
|
|
107
|
-
|
|
110
|
+
function parsePemBoundaryLine(e, t) {
|
|
111
|
+
let n = `-----${t} `, r = trimLwsp(e);
|
|
112
|
+
if (!r.startsWith(n) || !r.endsWith("-----")) return;
|
|
113
|
+
let i = r.slice(n.length, -5);
|
|
114
|
+
return isPemLabel(i) ? i : void 0;
|
|
115
|
+
}
|
|
116
|
+
/** RFC 7468 §2: data before the encapsulation boundaries is permitted. */
|
|
117
|
+
function findPreEncapsulationBoundary(e) {
|
|
118
|
+
for (let [t, n] of e.entries()) {
|
|
119
|
+
if (parsePemBoundaryLine(n, "BEGIN") !== void 0) return t;
|
|
120
|
+
if (looksLikePemBoundary(n)) return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function looksLikePemBoundary(e) {
|
|
124
|
+
return /^[ \t]*-{5,}(?:BEGIN|END)/.test(e);
|
|
125
|
+
}
|
|
126
|
+
/** RFC 822 §3.2: `field-name = 1*<any CHAR, excluding CTLs, SPACE, and ":">`. */
|
|
127
|
+
const o = /^[\x21-\x39\x3b-\x7e]+$/;
|
|
128
|
+
/** RFC 822 §3.3: `LWSP-char = SPACE / HTAB`. */
|
|
129
|
+
function isLwspChar(e) {
|
|
130
|
+
return e === " " || e === " ";
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Strips the whitespace surrounding a PEM document: `LWSP-char`s and the line
|
|
134
|
+
* terminators that separate the boundary lines from the body.
|
|
135
|
+
*
|
|
136
|
+
* `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode
|
|
137
|
+
* `Zs`, making those characters acceptable at a document edge while
|
|
138
|
+
* {@linkcode parsePemBoundaryLine} rejects them everywhere else.
|
|
139
|
+
*/
|
|
140
|
+
function trimPemDocument(e) {
|
|
141
|
+
return e.replace(/^[ \t\n]+|[ \t\n]+$/g, "");
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* @internal Strips surrounding RFC 822 §3.3 `LWSP-char`s.
|
|
145
|
+
*
|
|
146
|
+
* `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode `Zs`,
|
|
147
|
+
* none of which the grammar admits.
|
|
148
|
+
*/
|
|
149
|
+
function trimLwsp(e) {
|
|
150
|
+
return e.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* @internal Parses a PEM block with RFC 1421 §4.6 encapsulated headers.
|
|
154
|
+
*
|
|
155
|
+
* RFC 7468 §2 forbids headers, so this path exists only for the legacy
|
|
156
|
+
* OpenSSL-style encrypted PKCS#1 and SEC1 blocks that predate it.
|
|
157
|
+
*/
|
|
158
|
+
function parseTraditionalPemOrThrow(e) {
|
|
159
|
+
let t = trimPemDocument(e.replace(/\r\n?/g, "\n")).split("\n"), n = parsePemBoundaryLine(t[0] ?? "", "BEGIN");
|
|
160
|
+
if (n === void 0 || t.length < 2) throw Error("Invalid PEM block");
|
|
161
|
+
if (parsePemBoundaryLine(t[t.length - 1] ?? "", "END") !== n) throw Error("PEM boundaries do not match");
|
|
162
|
+
let r = /* @__PURE__ */ new Map(), i = 1, a;
|
|
163
|
+
for (; i < t.length - 1;) {
|
|
164
|
+
let e = t[i];
|
|
165
|
+
if (e === void 0) break;
|
|
166
|
+
if (e.length === 0) {
|
|
167
|
+
i += 1;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
if (a !== void 0 && isLwspChar(e.charAt(0))) {
|
|
171
|
+
r.set(a, `${r.get(a) ?? ""}${e}`), i += 1;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
let n = e.indexOf(":");
|
|
175
|
+
if (n === -1) break;
|
|
176
|
+
let s = e.slice(0, n);
|
|
177
|
+
if (!o.test(s)) throw Error(`Invalid PEM header name: ${s}`);
|
|
178
|
+
if (r.has(s)) throw Error(`Duplicate PEM header: ${s}`);
|
|
179
|
+
r.set(s, e.slice(n + 1).replace(/^[ \t]+/, "")), a = s, i += 1;
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
label: n,
|
|
183
|
+
headers: r,
|
|
184
|
+
base64Body: t.slice(i, t.length - 1).join("")
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function isPemLabel(e) {
|
|
188
|
+
return a.exec(e)?.[0] === e;
|
|
108
189
|
}
|
|
109
190
|
/**
|
|
110
191
|
* Extracts and base64-decodes the DER content from a PEM string.
|
|
192
|
+
* Text ahead of the `BEGIN` line is ignored.
|
|
111
193
|
*
|
|
112
194
|
* Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`
|
|
113
195
|
* markers don't match `label` or the body is not valid base64. For the
|
|
@@ -148,6 +230,6 @@ function toPemResult(e, t) {
|
|
|
148
230
|
}
|
|
149
231
|
}
|
|
150
232
|
//#endregion
|
|
151
|
-
export { categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
|
|
233
|
+
export { categorizePemBlocks, categorizePemBlocksOrThrow, parseTraditionalPemOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow, trimLwsp };
|
|
152
234
|
|
|
153
235
|
//# sourceMappingURL=pem.js.map
|
package/dist/pem/pem.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pem.js","names":[],"sources":["../../src/pem/pem.ts"],"sourcesContent":["/**\n * PEM helpers used across the public API.\n *\n * Encodes, decodes, splits, and categorizes PEM blocks as defined by\n * RFC 7468.\n *\n * @module\n */\n\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */\nexport interface PemBlock {\n\t/** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `\"CERTIFICATE\"`). */\n\treadonly label: string;\n\t/** Decoded DER content of this block. */\n\treadonly bytes: Uint8Array;\n\t/** The original PEM text including `BEGIN`/`END` lines. */\n\treadonly pem: string;\n}\n\n/**\n * PEM blocks grouped by their label into well-known PKI categories.\n * Blocks that don't match any known label land in {@linkcode others}.\n */\nexport interface CategorizedPemBlocks {\n\t/** Blocks with label `CERTIFICATE`. */\n\treadonly certificates: readonly PemBlock[];\n\t/** Blocks with label `CERTIFICATE REQUEST`. */\n\treadonly certificateRequests: readonly PemBlock[];\n\t/** Blocks with label `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY`. */\n\treadonly privateKeys: readonly PemBlock[];\n\t/** Blocks with label `PUBLIC KEY`. */\n\treadonly publicKeys: readonly PemBlock[];\n\t/** Blocks whose label doesn't match any of the above categories. */\n\treadonly others: readonly PemBlock[];\n}\n\n/**\n * Wraps DER bytes in a PEM envelope with 64-character base64 lines.\n *\n * @param label PEM type label (e.g. `\"CERTIFICATE\"`, `\"PRIVATE KEY\"`).\n * @param der Raw DER-encoded content.\n */\nexport function pemEncode(label: string, der: Uint8Array): string {\n\tconst body = base64Encode(der);\n\tconst lines = body.match(/.{1,64}/g) ?? [];\n\treturn `-----BEGIN ${label}-----\\n${lines.join('\\n')}\\n-----END ${label}-----`;\n}\n\n/** Machine-readable failure reason for the PEM decoders. */\nexport type PemErrorCode = 'malformed';\n\n/** Structured failure payload for PEM decoding. */\nexport interface PemFailure extends Micro509Error<PemErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode pemDecode}. */\nexport type PemDecodeResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode splitPemBlocks}. */\nexport type SplitPemBlocksResult =\n\t| { readonly ok: true; readonly value: readonly PemBlock[] }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode categorizePemBlocks}. */\nexport type CategorizePemBlocksResult =\n\t| { readonly ok: true; readonly value: CategorizedPemBlocks }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/**\n * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the\n * DER content from a PEM string. Throws if the `BEGIN`/`END` markers don't\n * match `label`.\n *\n * @param label Expected PEM type label.\n * @param pem PEM-encoded text (may contain `\\r`).\n */\nexport function pemDecodeOrThrow(label: string, pem: string): Uint8Array {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst begin = `-----BEGIN ${label}-----`;\n\tconst end = `-----END ${label}-----`;\n\tconst lines = normalized.split('\\n');\n\tif (lines[0] !== begin || lines[lines.length - 1] !== end || lines.length < 3) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns\n * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files\n * and ignores non-PEM text between blocks.\n */\nexport function splitPemBlocksOrThrow(input: string): readonly PemBlock[] {\n\tconst normalized = input.replace(/\\r/g, '');\n\tconst blocks: PemBlock[] = [];\n\tconst beginToken = '-----BEGIN ';\n\t// Linear `indexOf` scan rather than a global regex with a lazy body: a\n\t// backtracking pattern like `([\\s\\S]*?)…\\1` is polynomial on many unclosed\n\t// BEGIN markers (ReDoS). `indexOf` advances monotonically, so this stays O(n)\n\t// while preserving the original block/gap/label semantics.\n\tlet cursor = 0;\n\tlet scan = 0;\n\twhile (scan < normalized.length) {\n\t\tconst beginIdx = normalized.indexOf(beginToken, scan);\n\t\tif (beginIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst labelStart = beginIdx + beginToken.length;\n\t\tconst dashIdx = normalized.indexOf('-----', labelStart);\n\t\tif (dashIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst label = normalized.slice(labelStart, dashIdx);\n\t\tconst beginLineEnd = dashIdx + 5;\n\t\t// A well-formed begin line is `-----BEGIN <label>-----\\n` with a dash-free,\n\t\t// single-line label (RFC 7468). Anything else is not a block start; skip it\n\t\t// so it surfaces in the stray-marker checks instead of being parsed.\n\t\tif (\n\t\t\tlabel.length === 0 ||\n\t\t\tlabel.includes('-') ||\n\t\t\tlabel.includes('\\n') ||\n\t\t\tnormalized[beginLineEnd] !== '\\n'\n\t\t) {\n\t\t\tscan = labelStart;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bodyStart = beginLineEnd + 1;\n\t\tconst endToken = `\\n-----END ${label}-----`;\n\t\tconst endIdx = normalized.indexOf(endToken, bodyStart);\n\t\tif (endIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst blockEnd = endIdx + endToken.length;\n\t\tconst pem = normalized.slice(beginIdx, blockEnd);\n\t\tif (containsPemMarker(normalized.slice(cursor, beginIdx))) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\t\tblocks.push({\n\t\t\tlabel,\n\t\t\tbytes: pemDecodeOrThrow(label, pem),\n\t\t\tpem,\n\t\t});\n\t\tcursor = blockEnd;\n\t\tscan = blockEnd;\n\t}\n\tif (containsPemMarker(normalized.slice(cursor))) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n */\nexport function categorizePemBlocksOrThrow(\n\tinput: string | readonly PemBlock[],\n): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocksOrThrow(input) : input;\n\tconst certificates: PemBlock[] = [];\n\tconst certificateRequests: PemBlock[] = [];\n\tconst privateKeys: PemBlock[] = [];\n\tconst publicKeys: PemBlock[] = [];\n\tconst others: PemBlock[] = [];\n\n\tfor (const block of blocks) {\n\t\tswitch (block.label) {\n\t\t\tcase 'CERTIFICATE':\n\t\t\t\tcertificates.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'CERTIFICATE REQUEST':\n\t\t\t\tcertificateRequests.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE KEY':\n\t\t\tcase 'RSA PRIVATE KEY':\n\t\t\tcase 'EC PRIVATE KEY':\n\t\t\t\tprivateKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PUBLIC KEY':\n\t\t\t\tpublicKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tothers.push(block);\n\t\t}\n\t}\n\n\treturn { certificates, certificateRequests, privateKeys, publicKeys, others };\n}\n\nfunction normalizePemBodyLines(lines: readonly string[]): readonly string[] | undefined {\n\tconst normalizedLines = lines.map((line) => line.replace(/[ \\t]/g, ''));\n\tconst nonEmptyLines = normalizedLines.filter((line) => line !== '');\n\tif (nonEmptyLines.length === 0) {\n\t\treturn [''];\n\t}\n\treturn nonEmptyLines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line)) ? nonEmptyLines : undefined;\n}\n\nfunction containsPemMarker(value: string): boolean {\n\treturn value.includes('-----BEGIN ') || value.includes('-----END ');\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label` or the body is not valid base64. For the\n * throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem), 'Invalid PEM');\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them\n * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and\n * ignores non-PEM text between blocks.\n *\n * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM\n * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.\n */\nexport function splitPemBlocks(input: string): SplitPemBlocksResult {\n\treturn toPemResult(() => splitPemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n *\n * Returns a typed failure (`code: 'malformed'`) when raw text contains stray\n * or truncated PEM markers. For the throwing form use\n * {@linkcode categorizePemBlocksOrThrow}.\n */\nexport function categorizePemBlocks(\n\tinput: string | readonly PemBlock[],\n): CategorizePemBlocksResult {\n\treturn toPemResult(() => categorizePemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/** Shared Result wrapper around the throwing PEM cores. */\nfunction toPemResult<TValue>(\n\toperation: () => TValue,\n\tfallbackMessage: string,\n):\n\t| { readonly ok: true; readonly value: TValue }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure> {\n\ttry {\n\t\treturn successResult(operation());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : fallbackMessage);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8CA,SAAgB,UAAU,GAAe,GAAyB;CAGjE,OAAO,cAAc,EAAM,UAFd,EAAa,CACT,CAAC,CAAC,MAAM,UAAU,KAAK,CAAC,EAAA,CACC,KAAK,IAAI,EAAE,aAAa,EAAM;AACzE;;;;;;;;;AAkCA,SAAgB,iBAAiB,GAAe,GAAyB;CACxE,IAAM,IAAa,EAAI,QAAQ,OAAO,EAAE,CAAC,CAAC,KAAK,GACzC,IAAQ,cAAc,EAAM,QAC5B,IAAM,YAAY,EAAM,QACxB,IAAQ,EAAW,MAAM,IA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,EAAc,EAAU,CAAC;CACjC,SAAS,GAAO;EAEf,OADA,EAAmB,CAAK,GACjB,EAAc,aAAa,aAAiB,QAAQ,EAAM,UAAU,CAAe;CAC3F;AACD"}
|
|
1
|
+
{"version":3,"file":"pem.js","names":[],"sources":["../../src/pem/pem.ts"],"sourcesContent":["/**\n * PEM helpers used across the public API.\n *\n * Encodes, decodes, splits, and categorizes PEM blocks as defined by\n * RFC 7468.\n *\n * @module\n */\n\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */\nexport interface PemBlock {\n\t/** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `\"CERTIFICATE\"`). */\n\treadonly label: string;\n\t/** Decoded DER content of this block. */\n\treadonly bytes: Uint8Array;\n\t/** The original PEM text including `BEGIN`/`END` lines. */\n\treadonly pem: string;\n}\n\n/**\n * PEM blocks grouped by their label into well-known PKI categories.\n * Blocks that don't match any known label land in {@linkcode others}.\n */\nexport interface CategorizedPemBlocks {\n\t/** Blocks with label `CERTIFICATE`. */\n\treadonly certificates: readonly PemBlock[];\n\t/** Blocks with label `CERTIFICATE REQUEST`. */\n\treadonly certificateRequests: readonly PemBlock[];\n\t/** Blocks with label `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY`. */\n\treadonly privateKeys: readonly PemBlock[];\n\t/** Blocks with label `PUBLIC KEY`. */\n\treadonly publicKeys: readonly PemBlock[];\n\t/** Blocks whose label doesn't match any of the above categories. */\n\treadonly others: readonly PemBlock[];\n}\n\n// RFC 7468 §3 label ABNF: labelchar = %x21-2C / %x2E-7E, joined by an optional\n// single \"-\" or SP; an empty label is legal.\nconst PEM_LABEL_PATTERN = /^(?:[!-,.-~](?:[- ]?[!-,.-~])*)?$/;\n\n/**\n * Wraps DER bytes in a PEM envelope with 64-character base64 lines.\n *\n * @param label PEM type label (e.g. `\"CERTIFICATE\"`, `\"PRIVATE KEY\"`).\n * @param der Raw DER-encoded content.\n */\nexport function pemEncode(label: string, der: Uint8Array): string {\n\tif (!isPemLabel(label)) {\n\t\tthrow new Error('Invalid PEM label');\n\t}\n\tconst body = base64Encode(der);\n\tconst lines = body.match(/.{1,64}/g) ?? [];\n\treturn `-----BEGIN ${label}-----\\n${lines.join('\\n')}\\n-----END ${label}-----\\n`;\n}\n\n/** Machine-readable failure reason for the PEM decoders. */\nexport type PemErrorCode = 'malformed';\n\n/** Structured failure payload for PEM decoding. */\nexport interface PemFailure extends Micro509Error<PemErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode pemDecode}. */\nexport type PemDecodeResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode splitPemBlocks}. */\nexport type SplitPemBlocksResult =\n\t| { readonly ok: true; readonly value: readonly PemBlock[] }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode categorizePemBlocks}. */\nexport type CategorizePemBlocksResult =\n\t| { readonly ok: true; readonly value: CategorizedPemBlocks }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/**\n * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the\n * DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.\n * Throws if the `BEGIN`/`END` markers don't match `label`.\n *\n * @param label Expected PEM type label.\n * @param pem PEM-encoded text (may contain `\\r`).\n */\nexport function pemDecodeOrThrow(label: string, pem: string): Uint8Array {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst begin = findPreEncapsulationBoundary(lines);\n\tif (\n\t\tbegin === undefined ||\n\t\tparsePemBoundaryLine(lines[begin] ?? '', 'BEGIN') !== label ||\n\t\tparsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label ||\n\t\tlines.length - begin < 3\n\t) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(begin + 1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns\n * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files\n * and ignores non-PEM text between blocks.\n */\nexport function splitPemBlocksOrThrow(input: string): readonly PemBlock[] {\n\tconst normalized = input.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n');\n\tconst blocks: PemBlock[] = [];\n\tlet openBlock: { readonly label: string; readonly start: number } | undefined;\n\tlet lineStart = 0;\n\twhile (lineStart < normalized.length) {\n\t\tconst newline = normalized.indexOf('\\n', lineStart);\n\t\tconst lineEnd = newline === -1 ? normalized.length : newline;\n\t\tconst nextLineStart = newline === -1 ? normalized.length : newline + 1;\n\t\tconst line = normalized.slice(lineStart, lineEnd);\n\t\tconst beginLine = line.replace(/^[ \\t]+/, '');\n\t\tconst beginLabel = parsePemBoundaryLine(line, 'BEGIN');\n\t\tconst endLabel = parsePemBoundaryLine(line, 'END');\n\n\t\tif (beginLabel !== undefined) {\n\t\t\tif (openBlock !== undefined) {\n\t\t\t\tthrow new Error('Malformed PEM block');\n\t\t\t}\n\t\t\topenBlock = { label: beginLabel, start: lineStart + line.length - beginLine.length };\n\t\t} else if (endLabel !== undefined) {\n\t\t\tblocks.push(closePemBlock(normalized, openBlock, endLabel, nextLineStart));\n\t\t\topenBlock = undefined;\n\t\t} else if (looksLikePemBoundary(line)) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\n\t\tif (newline === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tlineStart = nextLineStart;\n\t}\n\tif (openBlock !== undefined) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\n}\n\nfunction closePemBlock(\n\tinput: string,\n\topenBlock: { readonly label: string; readonly start: number } | undefined,\n\tendLabel: string,\n\tend: number,\n): PemBlock {\n\tif (openBlock === undefined || openBlock.label !== endLabel) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\tconst pem = input.slice(openBlock.start, end);\n\treturn {\n\t\tlabel: openBlock.label,\n\t\tbytes: pemDecodeOrThrow(openBlock.label, pem),\n\t\tpem,\n\t};\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n */\nexport function categorizePemBlocksOrThrow(\n\tinput: string | readonly PemBlock[],\n): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocksOrThrow(input) : input;\n\tconst certificates: PemBlock[] = [];\n\tconst certificateRequests: PemBlock[] = [];\n\tconst privateKeys: PemBlock[] = [];\n\tconst publicKeys: PemBlock[] = [];\n\tconst others: PemBlock[] = [];\n\n\tfor (const block of blocks) {\n\t\tswitch (block.label) {\n\t\t\tcase 'CERTIFICATE':\n\t\t\t\tcertificates.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'CERTIFICATE REQUEST':\n\t\t\t\tcertificateRequests.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE KEY':\n\t\t\tcase 'RSA PRIVATE KEY':\n\t\t\tcase 'EC PRIVATE KEY':\n\t\t\t\tprivateKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PUBLIC KEY':\n\t\t\t\tpublicKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tothers.push(block);\n\t\t}\n\t}\n\n\treturn { certificates, certificateRequests, privateKeys, publicKeys, others };\n}\n\nfunction normalizePemBodyLines(lines: readonly string[]): readonly string[] | undefined {\n\tconst normalizedLines = lines.map((line) => line.replace(/[ \\t]/g, ''));\n\tconst nonEmptyLines = normalizedLines.filter((line) => line !== '');\n\tif (nonEmptyLines.length === 0) {\n\t\treturn [''];\n\t}\n\treturn nonEmptyLines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line)) ? nonEmptyLines : undefined;\n}\n\nfunction parsePemBoundaryLine(line: string, kind: 'BEGIN' | 'END'): string | undefined {\n\tconst prefix = `-----${kind} `;\n\tconst withoutSurroundingWsp = trimLwsp(line);\n\tif (!withoutSurroundingWsp.startsWith(prefix) || !withoutSurroundingWsp.endsWith('-----')) {\n\t\treturn undefined;\n\t}\n\tconst label = withoutSurroundingWsp.slice(prefix.length, -5);\n\treturn isPemLabel(label) ? label : undefined;\n}\n\n/** RFC 7468 §2: data before the encapsulation boundaries is permitted. */\nfunction findPreEncapsulationBoundary(lines: readonly string[]): number | undefined {\n\tfor (const [index, line] of lines.entries()) {\n\t\tif (parsePemBoundaryLine(line, 'BEGIN') !== undefined) {\n\t\t\treturn index;\n\t\t}\n\t\tif (looksLikePemBoundary(line)) {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction looksLikePemBoundary(line: string): boolean {\n\treturn /^[ \\t]*-{5,}(?:BEGIN|END)/.test(line);\n}\n\n/** RFC 822 §3.2: `field-name = 1*<any CHAR, excluding CTLs, SPACE, and \":\">`. */\nconst RFC822_FIELD_NAME = /^[\\x21-\\x39\\x3b-\\x7e]+$/;\n\n/** RFC 822 §3.3: `LWSP-char = SPACE / HTAB`. */\nfunction isLwspChar(character: string): boolean {\n\treturn character === ' ' || character === '\\t';\n}\n\n/**\n * Strips the whitespace surrounding a PEM document: `LWSP-char`s and the line\n * terminators that separate the boundary lines from the body.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode\n * `Zs`, making those characters acceptable at a document edge while\n * {@linkcode parsePemBoundaryLine} rejects them everywhere else.\n */\nfunction trimPemDocument(value: string): string {\n\treturn value.replace(/^[ \\t\\n]+|[ \\t\\n]+$/g, '');\n}\n\n/**\n * @internal Strips surrounding RFC 822 §3.3 `LWSP-char`s.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode `Zs`,\n * none of which the grammar admits.\n */\nexport function trimLwsp(value: string): string {\n\treturn value.replace(/^[ \\t]+|[ \\t]+$/g, '');\n}\n\n/** A PEM block carrying RFC 1421 §4.6 encapsulated headers ahead of its body. */\nexport interface TraditionalPemBlock {\n\t/** PEM type label between the `BEGIN` / `END` markers. */\n\treadonly label: string;\n\t/** Encapsulated headers (e.g. `Proc-Type`, `DEK-Info`), unfolded. */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n}\n\n/**\n * @internal Parses a PEM block with RFC 1421 §4.6 encapsulated headers.\n *\n * RFC 7468 §2 forbids headers, so this path exists only for the legacy\n * OpenSSL-style encrypted PKCS#1 and SEC1 blocks that predate it.\n */\nexport function parseTraditionalPemOrThrow(pem: string): TraditionalPemBlock {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst label = parsePemBoundaryLine(lines[0] ?? '', 'BEGIN');\n\tif (label === undefined || lines.length < 2) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tif (parsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\tlet foldedName: string | undefined;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (foldedName !== undefined && isLwspChar(line.charAt(0))) {\n\t\t\theaders.set(foldedName, `${headers.get(foldedName) ?? ''}${line}`);\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst delimiter = line.indexOf(':');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (!RFC822_FIELD_NAME.test(headerName)) {\n\t\t\tthrow new Error(`Invalid PEM header name: ${headerName}`);\n\t\t}\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 1).replace(/^[ \\t]+/, ''));\n\t\tfoldedName = headerName;\n\t\tindex += 1;\n\t}\n\treturn { label, headers, base64Body: lines.slice(index, lines.length - 1).join('') };\n}\n\nfunction isPemLabel(label: string): boolean {\n\treturn PEM_LABEL_PATTERN.exec(label)?.[0] === label;\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\n * Text ahead of the `BEGIN` line is ignored.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label` or the body is not valid base64. For the\n * throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem), 'Invalid PEM');\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them\n * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and\n * ignores non-PEM text between blocks.\n *\n * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM\n * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.\n */\nexport function splitPemBlocks(input: string): SplitPemBlocksResult {\n\treturn toPemResult(() => splitPemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n *\n * Returns a typed failure (`code: 'malformed'`) when raw text contains stray\n * or truncated PEM markers. For the throwing form use\n * {@linkcode categorizePemBlocksOrThrow}.\n */\nexport function categorizePemBlocks(\n\tinput: string | readonly PemBlock[],\n): CategorizePemBlocksResult {\n\treturn toPemResult(() => categorizePemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/** Shared Result wrapper around the throwing PEM cores. */\nfunction toPemResult<TValue>(\n\toperation: () => TValue,\n\tfallbackMessage: string,\n):\n\t| { readonly ok: true; readonly value: TValue }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure> {\n\ttry {\n\t\treturn successResult(operation());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : fallbackMessage);\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA0CA,MAAM,IAAoB;;;;;;;AAQ1B,SAAgB,UAAU,GAAe,GAAyB;CACjE,IAAI,CAAC,WAAW,CAAK,GACpB,MAAU,MAAM,mBAAmB;CAIpC,OAAO,cAAc,EAAM,UAFd,EAAa,CACT,CAAC,CAAC,MAAM,UAAU,KAAK,CAAC,EAAA,CACC,KAAK,IAAI,EAAE,aAAa,EAAM;AACzE;;;;;;;;;AAkCA,SAAgB,iBAAiB,GAAe,GAAyB;CAExE,IAAM,IADa,gBAAgB,EAAI,QAAQ,UAAU,IAAI,CACtC,CAAC,CAAC,MAAM,IAAI,GAC7B,IAAQ,6BAA6B,CAAK;CAChD,IACC,MAAU,KAAA,KACV,qBAAqB,EAAM,MAAU,IAAI,OAAO,MAAM,KACtD,qBAAqB,EAAM,EAAM,SAAS,MAAM,IAAI,KAAK,MAAM,KAC/D,EAAM,SAAS,IAAQ,GAEvB,MAAU,MAAM,mBAAmB,GAAO;CAE3C,IAAM,IAAY,sBAAsB,EAAM,MAAM,IAAQ,GAAG,EAAE,CAAC;CAClE,IAAI,MAAc,KAAA,GACjB,MAAU,MAAM,mBAAmB,GAAO;CAE3C,IAAI;EACH,OAAO,EAAa,EAAU,KAAK,EAAE,CAAC;CACvC,QAAQ;EACP,MAAU,MAA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ACb,KAAS;CACV;CACA,OAAO;EAAE;EAAO;EAAS,YAAY,EAAM,MAAM,GAAO,EAAM,SAAS,CAAC,CAAC,CAAC,KAAK,EAAE;CAAE;AACpF;AAEA,SAAS,WAAW,GAAwB;CAC3C,OAAO,EAAkB,KAAK,CAAK,CAAC,GAAG,OAAO;AAC/C;;;;;;;;;AAUA,SAAgB,UAAU,GAAe,GAA8B;CACtE,OAAO,kBAAkB,iBAAiB,GAAO,CAAG,GAAG,aAAa;AACrE;;;;;;;;;AAUA,SAAgB,eAAe,GAAqC;CACnE,OAAO,kBAAkB,sBAAsB,CAAK,GAAG,qBAAqB;AAC7E;;;;;;;;;;AAWA,SAAgB,oBACf,GAC4B;CAC5B,OAAO,kBAAkB,2BAA2B,CAAK,GAAG,qBAAqB;AAClF;;AAGA,SAAS,YACR,GACA,GAG8D;CAC9D,IAAI;EACH,OAAO,EAAc,EAAU,CAAC;CACjC,SAAS,GAAO;EAEf,OADA,EAAmB,CAAK,GACjB,EAAc,aAAa,aAAiB,QAAQ,EAAM,UAAU,CAAe;CAC3F;AACD"}
|
package/dist/pkcs/pkcs12-mac.js
CHANGED
|
@@ -25,7 +25,7 @@ async function createPkcs12MacData(e, a) {
|
|
|
25
25
|
der: o([
|
|
26
26
|
o([o([r(d.sha256), n()]), i(l)]),
|
|
27
27
|
i(c),
|
|
28
|
-
t(s)
|
|
28
|
+
...s === 1 ? [] : [t(s)]
|
|
29
29
|
]),
|
|
30
30
|
parsed: {
|
|
31
31
|
digestAlgorithmOid: d.sha256,
|
|
@@ -43,14 +43,14 @@ async function createPkcs12MacData(e, a) {
|
|
|
43
43
|
*/
|
|
44
44
|
async function parsePkcs12MacDataOrThrow(e, t, n) {
|
|
45
45
|
let r = a(e), i = r[0], o = r[1], l = r[2];
|
|
46
|
-
if (r.length !== 3 || i === void 0 || o === void 0 || l
|
|
46
|
+
if (r.length !== 2 && r.length !== 3 || i === void 0 || o === void 0 || o.tag !== 4 || l !== void 0 && l.tag !== 2) throw Error("Malformed MacData");
|
|
47
47
|
let f = e.slice(i.start - i.headerLength, i.end), p = a(f), m = p[0], h = p[1];
|
|
48
48
|
if (p.length !== 2 || m === void 0 || h === void 0 || h.tag !== 4) throw Error("Malformed DigestInfo");
|
|
49
49
|
let _ = a(f.slice(m.start - m.headerLength, m.end)), v = _[0];
|
|
50
50
|
if (v === void 0 || _.length !== 1 && _.length !== 2) throw Error("MacData algorithm missing");
|
|
51
51
|
let y = c(v.value);
|
|
52
52
|
if (y !== d.sha256) throw Error("Only SHA-256 PKCS#12 MAC is supported");
|
|
53
|
-
let b = s(l.value, "MacData iterations");
|
|
53
|
+
let b = l === void 0 ? 1 : s(l.value, "MacData iterations");
|
|
54
54
|
if (assertPkcs12MacIterations(b), n === void 0) return {
|
|
55
55
|
digestAlgorithmOid: y,
|
|
56
56
|
digestAlgorithmName: g(y),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pkcs12-mac.js","names":[],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based HMAC-SHA-256 integrity check\n * defined in PKCS#12 (RFC 7292), using the PKCS#12 key-derivation scheme.\n *\n * @module\n */\n\nimport {\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** Input for {@linkcode createPkcs12MacData}. */\nexport interface Pkcs12MacOptions {\n\t/** Password used to derive the HMAC key via the PKCS#12 KDF. */\n\treadonly password: string;\n\t/** PKCS#12 KDF iteration count. Default: `2048`. */\n\treadonly iterations?: number;\n\t/** Random salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n}\n\n/** Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. */\nexport interface ParsedPkcs12MacData {\n\t/** OID of the digest algorithm (currently always SHA-256). */\n\treadonly digestAlgorithmOid: string;\n\t/** Human-readable digest algorithm name (currently `\"SHA-256\"`). */\n\treadonly digestAlgorithmName: string;\n\t/** Hex-encoded MAC digest value. */\n\treadonly digestHex: string;\n\t/** Hex-encoded salt bytes used during key derivation. */\n\treadonly saltHex: string;\n\t/** Number of PKCS#12 KDF iterations. */\n\treadonly iterations: number;\n\t/**\n\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t */\n\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n}\n\n/**\n * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns\n * the DER-encoded MacData block alongside its parsed representation.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tconst iterations = options.iterations ?? 2048;\n\tassertPkcs12MacIterations(iterations);\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\tintegerFromNumber(iterations),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode = 'malformed';\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsedPkcs12MacData> {\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\ttop.length !== 3 ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrow new Error('Only SHA-256 PKCS#12 MAC is supported');\n\t}\n\tconst parsedIterations = decodeNonNegativeIntegerNumber(iterations.value, 'MacData iterations');\n\tassertPkcs12MacIterations(parsedIterations);\n\tif (password === undefined) {\n\t\treturn {\n\t\t\tdigestAlgorithmOid,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\t\tdigestHex: toHex(digest.value),\n\t\t\tsaltHex: toHex(salt.value),\n\t\t\titerations: parsedIterations,\n\t\t\tverification: 'unchecked',\n\t\t};\n\t}\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(await parsePkcs12MacDataOrThrow(der, authenticatedSafe, password));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed MacData');\n\t}\n}\n\nfunction assertPkcs12MacIterations(iterations: number): void {\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.sign('HMAC', key, toArrayBuffer(authenticatedSafe)),\n\t);\n}\n\n/** PKCS#12 key derivation (RFC 7292 Appendix B). `id` selects the purpose (3 = MAC key). */\nasync function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: number,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst S = repeatToMultiple(salt, v);\n\tconst P = repeatToMultiple(passwordBytes, v);\n\tlet I = concatBytes([S, P]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (I.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tconst next = new Uint8Array(I.length);\n\t\tfor (let blockIndex = 0; blockIndex < I.length / v; blockIndex += 1) {\n\t\t\tconst block = I.slice(blockIndex * v, blockIndex * v + v);\n\t\t\taddBlockInPlace(block, B);\n\t\t\tnext.set(block, blockIndex * v);\n\t\t}\n\t\tI = next;\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated UCS-2 big-endian byte array (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+DA,eAAsB,oBACrB,GACA,GAME;CACF,IAAM,IAAa,EAAQ,cAAc;CACzC,0BAA0B,CAAU;CACpC,IAAM,IAAO,EAAQ,QAAQ,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACrE,IAAM,MAAM,iBAAiB,GAAmB,EAAQ,UAAU,GAAM,CAAU;CAMxF,OAAO;EACN,KANW,EAAS;GACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,GAAG,EAAU,CAAC,CAAC,GAAG,EAAY,CAAG,CAAC,CAAC;GACnF,EAAY,CAAI;GAChB,EAAkB,CAAU;EAC7B,CAEG;EACF,QAAQ;GACP,oBAAoB,EAAK;GACzB,qBAAqB,EAAsB,EAAK,MAAM;GACtD,WAAW,EAAM,CAAG;GACpB,SAAS,EAAM,CAAI;GACnB;GACA,cAAc;EACf;CACD;AACD;;;;;AAoBA,eAAsB,0BACrB,GACA,GACA,GAC+B;CAC/B,IAAM,IAAM,EAAqB,CAAG,GAC9B,IAAa,EAAI,IACjB,IAAO,EAAI,IACX,IAAa,EAAI;CACvB,IACC,EAAI,WAAW,KACf,MAAe,KAAA,KACf,MAAS,KAAA,KACT,MAAe,KAAA,KACf,EAAK,QAAQ,GAEb,MAAU,MAAM,mBAAmB;CAEpC,IAAM,IAAgB,EAAI,MAAM,EAAW,QAAQ,EAAW,cAAc,EAAW,GAAG,GACpF,IAAqB,EAAqB,CAAa,GACvD,IAAY,EAAmB,IAC/B,IAAS,EAAmB;CAClC,IACC,EAAmB,WAAW,KAC9B,MAAc,KAAA,KACd,MAAW,KAAA,KACX,EAAO,QAAQ,GAEf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AS,qBAAqB,GAA8B;CAC3D,IAAM,IAAM,IAAI,YAAY,EAAS,SAAS,KAAK,CAAC;CACpD,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAS,QAAQ,KAAS,GAAG;EACxD,IAAM,IAAO,EAAS,WAAW,CAAK;EAEtC,AADA,EAAI,IAAQ,KAAK,KAAQ,GACzB,EAAI,IAAQ,IAAI,KAAK,IAAO;CAC7B;CACA,OAAO;AACR;;AAGA,SAAS,iBAAiB,GAAmB,GAA0B;CAItE,OAHI,EAAM,WAAW,oBACb,IAAI,WAAW,IAEhB,eAAe,GAAO,IAAO,KAAK,KAAK,EAAM,SAAS,CAAI,CAAC;AACnE;;AAGA,SAAS,eAAe,GAAmB,GAA4B;CACtE,IAAM,IAAM,IAAI,WAAW,CAAM;CACjC,KAAK,IAAI,IAAQ,GAAG,IAAQ,GAAQ,KAAS,GAC5C,EAAI,KAAS,EAAM,IAAQ,EAAM,WAAW;CAE7C,OAAO;AACR;;AAGA,SAAS,gBAAgB,GAAmB,GAA0B;CACrE,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,EAAM,SAAS,GAAG,KAAS,GAAG,KAAY;EAC1D,IAAM,KAAO,EAAM,MAAU,MAAM,EAAO,MAAU,KAAK;EAEzD,AADA,EAAM,KAAS,IAAM,KACrB,IAAQ,KAAO;CAChB;AACD;;AAGA,SAAS,WAAW,GAAkB,GAA4B;CACjE,IAAI,EAAK,WAAW,EAAM,QACzB,OAAO;CAER,IAAI,IAAS;CACb,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAK,QAAQ,KAAS,GACjD,MAAW,EAAK,MAAU,MAAM,EAAM,MAAU;CAEjD,OAAO,MAAW;AACnB"}
|
|
1
|
+
{"version":3,"file":"pkcs12-mac.js","names":[],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based HMAC-SHA-256 integrity check\n * defined in PKCS#12 (RFC 7292), using the PKCS#12 key-derivation scheme.\n *\n * @module\n */\n\nimport {\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** Input for {@linkcode createPkcs12MacData}. */\nexport interface Pkcs12MacOptions {\n\t/** Password used to derive the HMAC key via the PKCS#12 KDF. */\n\treadonly password: string;\n\t/** PKCS#12 KDF iteration count. Default: `2048`. */\n\treadonly iterations?: number;\n\t/** Random salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n}\n\n/** Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. */\nexport interface ParsedPkcs12MacData {\n\t/** OID of the digest algorithm (currently always SHA-256). */\n\treadonly digestAlgorithmOid: string;\n\t/** Human-readable digest algorithm name (currently `\"SHA-256\"`). */\n\treadonly digestAlgorithmName: string;\n\t/** Hex-encoded MAC digest value. */\n\treadonly digestHex: string;\n\t/** Hex-encoded salt bytes used during key derivation. */\n\treadonly saltHex: string;\n\t/** Number of PKCS#12 KDF iterations. */\n\treadonly iterations: number;\n\t/**\n\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t */\n\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n}\n\n/**\n * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns\n * the DER-encoded MacData block alongside its parsed representation.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tconst iterations = options.iterations ?? 2048;\n\tassertPkcs12MacIterations(iterations);\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\t// iterations INTEGER DEFAULT 1 — X.690 §11.5 forbids encoding the default.\n\t\t...(iterations === 1 ? [] : [integerFromNumber(iterations)]),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode = 'malformed';\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsedPkcs12MacData> {\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\t(top.length !== 2 && top.length !== 3) ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\t(iterations !== undefined && iterations.tag !== 0x02)\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrow new Error('Only SHA-256 PKCS#12 MAC is supported');\n\t}\n\tconst parsedIterations =\n\t\titerations === undefined\n\t\t\t? 1\n\t\t\t: decodeNonNegativeIntegerNumber(iterations.value, 'MacData iterations');\n\tassertPkcs12MacIterations(parsedIterations);\n\tif (password === undefined) {\n\t\treturn {\n\t\t\tdigestAlgorithmOid,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\t\tdigestHex: toHex(digest.value),\n\t\t\tsaltHex: toHex(salt.value),\n\t\t\titerations: parsedIterations,\n\t\t\tverification: 'unchecked',\n\t\t};\n\t}\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(await parsePkcs12MacDataOrThrow(der, authenticatedSafe, password));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed MacData');\n\t}\n}\n\nfunction assertPkcs12MacIterations(iterations: number): void {\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.sign('HMAC', key, toArrayBuffer(authenticatedSafe)),\n\t);\n}\n\n/** PKCS#12 key derivation (RFC 7292 Appendix B). `id` selects the purpose (3 = MAC key). */\nasync function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: number,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst S = repeatToMultiple(salt, v);\n\tconst P = repeatToMultiple(passwordBytes, v);\n\tlet I = concatBytes([S, P]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (I.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tconst next = new Uint8Array(I.length);\n\t\tfor (let blockIndex = 0; blockIndex < I.length / v; blockIndex += 1) {\n\t\t\tconst block = I.slice(blockIndex * v, blockIndex * v + v);\n\t\t\taddBlockInPlace(block, B);\n\t\t\tnext.set(block, blockIndex * v);\n\t\t}\n\t\tI = next;\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated UCS-2 big-endian byte array (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+DA,eAAsB,oBACrB,GACA,GAME;CACF,IAAM,IAAa,EAAQ,cAAc;CACzC,0BAA0B,CAAU;CACpC,IAAM,IAAO,EAAQ,QAAQ,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACrE,IAAM,MAAM,iBAAiB,GAAmB,EAAQ,UAAU,GAAM,CAAU;CAOxF,OAAO;EACN,KAPW,EAAS;GACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,GAAG,EAAU,CAAC,CAAC,GAAG,EAAY,CAAG,CAAC,CAAC;GACnF,EAAY,CAAI;G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AM;CACjC,KAAK,IAAI,IAAQ,GAAG,IAAQ,GAAQ,KAAS,GAC5C,EAAI,KAAS,EAAM,IAAQ,EAAM,WAAW;CAE7C,OAAO;AACR;;AAGA,SAAS,gBAAgB,GAAmB,GAA0B;CACrE,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,EAAM,SAAS,GAAG,KAAS,GAAG,KAAY;EAC1D,IAAM,KAAO,EAAM,MAAU,MAAM,EAAO,MAAU,KAAK;EAEzD,AADA,EAAM,KAAS,IAAM,KACrB,IAAQ,KAAO;CAChB;AACD;;AAGA,SAAS,WAAW,GAAkB,GAA4B;CACjE,IAAI,EAAK,WAAW,EAAM,QACzB,OAAO;CAER,IAAI,IAAS;CACb,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAK,QAAQ,KAAS,GACjD,MAAW,EAAK,MAAU,MAAM,EAAM,MAAU;CAEjD,OAAO,MAAW;AACnB"}
|
package/dist/pkcs/pkcs7.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorResult, Micro509Error } from "../result/result.js";
|
|
2
|
-
import { ParsedCertificate, ParsedName } from "../x509/parse.js";
|
|
3
2
|
import { SignatureProfileInput } from "../internal/crypto/signing.js";
|
|
3
|
+
import { ParsedCertificate, ParsedName } from "../x509/parse.js";
|
|
4
4
|
//#region src/pkcs/pkcs7.d.ts
|
|
5
5
|
/** PEM text (may contain multiple CERTIFICATE blocks), raw DER bytes, or an already-parsed certificate. */
|
|
6
6
|
type Pkcs7CertificateSource = string | Uint8Array | ParsedCertificate;
|
|
@@ -13,16 +13,29 @@ interface Pkcs7CertBagMaterial {
|
|
|
13
13
|
/** Base64-encoded DER (no PEM armor). */
|
|
14
14
|
readonly base64: string;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* RFC 5652 §5.3 `SignerIdentifier ::= CHOICE { issuerAndSerialNumber,
|
|
18
|
+
* subjectKeyIdentifier [0] }`, which locates the signer's certificate.
|
|
19
|
+
*/
|
|
20
|
+
type ParsedSignerIdentifier = {
|
|
21
|
+
/** Issuer name plus serial number. */
|
|
22
|
+
readonly type: "issuerAndSerialNumber";
|
|
23
|
+
/** Parsed issuer distinguished name. */
|
|
24
|
+
readonly issuer: ParsedName;
|
|
25
|
+
/** Hex-encoded certificate serial number. */
|
|
26
|
+
readonly serialNumberHex: string;
|
|
27
|
+
} | {
|
|
28
|
+
/** SubjectKeyIdentifier (`[0]`). */
|
|
29
|
+
readonly type: "subjectKeyIdentifier";
|
|
30
|
+
/** Hex-encoded SubjectKeyIdentifier of the signer certificate. */
|
|
31
|
+
readonly subjectKeyIdentifier: string;
|
|
32
|
+
};
|
|
16
33
|
/** Fields shared by every decoded SignerInfo, regardless of signed-attribute presence. */
|
|
17
34
|
interface ParsedPkcs7SignerInfoBase {
|
|
18
35
|
/** CMS SignerInfo version (typically 1 for issuerAndSerialNumber). */
|
|
19
36
|
readonly version: number;
|
|
20
|
-
/**
|
|
21
|
-
readonly
|
|
22
|
-
/** Hex-encoded serial number used to locate the signer certificate, if present. */
|
|
23
|
-
readonly serialNumberHex?: string;
|
|
24
|
-
/** Hex-encoded SubjectKeyIdentifier used to locate the signer certificate, if present. */
|
|
25
|
-
readonly subjectKeyIdentifier?: string;
|
|
37
|
+
/** Which of the two RFC 5652 §5.3 SignerIdentifier alternatives this SignerInfo uses. */
|
|
38
|
+
readonly signerIdentifier: ParsedSignerIdentifier;
|
|
26
39
|
/** OID of the digest algorithm used to hash the content. */
|
|
27
40
|
readonly digestAlgorithmOid: string;
|
|
28
41
|
/** Human-readable digest algorithm name (e.g. `"SHA-256"`). */
|
|
@@ -55,6 +68,42 @@ type ParsedPkcs7SignerInfo = (ParsedPkcs7SignerInfoBase & {
|
|
|
55
68
|
/** Never present without signed attributes. */
|
|
56
69
|
readonly signedAttrsDer?: undefined;
|
|
57
70
|
});
|
|
71
|
+
/**
|
|
72
|
+
* One RFC 5652 §10.2.2 CertificateChoices alternative.
|
|
73
|
+
*
|
|
74
|
+
* X.509 is the only alternative this library decodes. The rest keep their DER,
|
|
75
|
+
* including the context tag, so a CertificateSet round-trips and a caller can
|
|
76
|
+
* tell an X.509-only bag from one carrying attribute certificates. RFC 5652
|
|
77
|
+
* marks `extendedCertificate` and `attributeCertificateV1` obsolete.
|
|
78
|
+
*/
|
|
79
|
+
type ParsedCertificateChoice = {
|
|
80
|
+
/** X.509 certificate (untagged `Certificate`). */
|
|
81
|
+
readonly type: "certificate";
|
|
82
|
+
/** The decoded certificate. */
|
|
83
|
+
readonly certificate: ParsedCertificate;
|
|
84
|
+
} | {
|
|
85
|
+
/** PKCS #6 extended certificate (`[0]`), obsolete. */
|
|
86
|
+
readonly type: "extendedCertificate";
|
|
87
|
+
/** Raw DER of the element, including its context tag. */
|
|
88
|
+
readonly der: Uint8Array;
|
|
89
|
+
} | {
|
|
90
|
+
/** Version 1 X.509 attribute certificate (`[1]`), obsolete. */
|
|
91
|
+
readonly type: "attributeCertificateV1";
|
|
92
|
+
/** Raw DER of the element, including its context tag. */
|
|
93
|
+
readonly der: Uint8Array;
|
|
94
|
+
} | {
|
|
95
|
+
/** Version 2 X.509 attribute certificate (`[2]`). */
|
|
96
|
+
readonly type: "attributeCertificateV2";
|
|
97
|
+
/** Raw DER of the element, including its context tag. */
|
|
98
|
+
readonly der: Uint8Array;
|
|
99
|
+
} | {
|
|
100
|
+
/** Any other certificate format (`[3] OtherCertificateFormat`). */
|
|
101
|
+
readonly type: "other";
|
|
102
|
+
/** `otherCertFormat` OID identifying the format. */
|
|
103
|
+
readonly formatOid: string;
|
|
104
|
+
/** Raw DER of the element, including its context tag. */
|
|
105
|
+
readonly der: Uint8Array;
|
|
106
|
+
};
|
|
58
107
|
/** Decoded PKCS#7 SignedData content, including certificates and signer info. */
|
|
59
108
|
interface ParsedPkcs7SignedData {
|
|
60
109
|
/** Original DER bytes when this object came from {@linkcode parsePkcs7SignedDataDer} or PEM parsing. */
|
|
@@ -71,8 +120,8 @@ interface ParsedPkcs7SignedData {
|
|
|
71
120
|
readonly encapsulatedContentTypeOid: string;
|
|
72
121
|
/** Raw encapsulated content bytes. Absent in degenerate (certs-only) bags. */
|
|
73
122
|
readonly encapsulatedContent?: Uint8Array;
|
|
74
|
-
/**
|
|
75
|
-
readonly
|
|
123
|
+
/** RFC 5652 §10.2.2 CertificateChoices entries from the SignedData certificate set. */
|
|
124
|
+
readonly certificateChoices: readonly ParsedCertificateChoice[];
|
|
76
125
|
/** Decoded signer info entries. Empty for degenerate cert bags. */
|
|
77
126
|
readonly signerInfos: readonly ParsedPkcs7SignerInfo[];
|
|
78
127
|
}
|
|
@@ -113,18 +162,26 @@ interface VerifyPkcs7SignedDataFailure extends Micro509Error<VerifyPkcs7SignedDa
|
|
|
113
162
|
/** Options for {@linkcode verifyPkcs7SignedData}. */
|
|
114
163
|
interface VerifyPkcs7SignedDataOptions {
|
|
115
164
|
/**
|
|
116
|
-
* External content for a detached SignedData (RFC 5652 Section 5.2, absent
|
|
117
|
-
*
|
|
118
|
-
* SignedData embeds its own content.
|
|
165
|
+
* External content for a detached SignedData (RFC 5652 Section 5.2, absent `eContent`).
|
|
166
|
+
* Required to verify a detached signature; ignored when the SignedData embeds its own content.
|
|
119
167
|
*/
|
|
120
168
|
readonly content?: Uint8Array;
|
|
121
169
|
}
|
|
170
|
+
/** A SignerInfo paired with the certificate that verified its signature. */
|
|
171
|
+
interface VerifiedPkcs7Signer {
|
|
172
|
+
/** The SignerInfo whose signature verified. */
|
|
173
|
+
readonly signerInfo: ParsedPkcs7SignerInfo;
|
|
174
|
+
/** The certificate from the SignedData certificate set that verified it. */
|
|
175
|
+
readonly certificate: ParsedCertificate;
|
|
176
|
+
}
|
|
122
177
|
/** Success-or-failure result from {@linkcode verifyPkcs7SignedData}. */
|
|
123
178
|
type VerifyPkcs7SignedDataResult = {
|
|
124
179
|
/** Verification succeeded. */
|
|
125
180
|
readonly ok: true;
|
|
126
181
|
/** The verified SignedData structure. */
|
|
127
182
|
readonly value: ParsedPkcs7SignedData;
|
|
183
|
+
/** One entry per SignerInfo, in SignedData order. */
|
|
184
|
+
readonly signers: readonly VerifiedPkcs7Signer[];
|
|
128
185
|
} | ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>;
|
|
129
186
|
/** Caller-correctable failure code from {@linkcode createPkcs7CertBag}. */
|
|
130
187
|
type CreatePkcs7CertBagErrorCode = "invalid_certificate";
|
|
@@ -189,17 +246,21 @@ interface CreatePkcs7SignedDataInput {
|
|
|
189
246
|
*/
|
|
190
247
|
readonly detached?: boolean;
|
|
191
248
|
}
|
|
192
|
-
/** DER, PEM, and base64 encodings of a PKCS#7 SignedData structure. */
|
|
249
|
+
/** DER, PEM, and base64 encodings of a PKCS#7/CMS SignedData structure. */
|
|
193
250
|
interface Pkcs7SignedDataMaterial {
|
|
194
|
-
/** Raw DER-encoded
|
|
251
|
+
/** Raw DER-encoded SignedData ContentInfo. */
|
|
195
252
|
readonly der: Uint8Array;
|
|
196
|
-
/**
|
|
253
|
+
/**
|
|
254
|
+
* PEM-armored ContentInfo. A version 1 SignedData carries the `PKCS7`
|
|
255
|
+
* label; a version 3 one is outside RFC 2315, whose SignedData version
|
|
256
|
+
* "shall be 1", so it carries the RFC 7468 Section 9 `CMS` label.
|
|
257
|
+
*/
|
|
197
258
|
readonly pem: string;
|
|
198
259
|
/** Base64-encoded DER (no PEM armor). */
|
|
199
260
|
readonly base64: string;
|
|
200
261
|
}
|
|
201
262
|
/** Caller-correctable failure codes from {@linkcode createPkcs7SignedData}. */
|
|
202
|
-
type CreatePkcs7SignedDataErrorCode = "no_signers" | "invalid_signer_certificate" | "invalid_certificate" | "unsupported_signer_key";
|
|
263
|
+
type CreatePkcs7SignedDataErrorCode = "no_signers" | "invalid_signer_certificate" | "invalid_certificate" | "signer_certificate_key_mismatch" | "unsupported_signer_key";
|
|
203
264
|
/** Error payload for a failed PKCS#7 SignedData creation. */
|
|
204
265
|
interface CreatePkcs7SignedDataFailure extends Micro509Error<CreatePkcs7SignedDataErrorCode> {
|
|
205
266
|
/** Always `false` for failures. */
|
|
@@ -228,17 +289,18 @@ type CreatePkcs7SignedDataResult = {
|
|
|
228
289
|
*
|
|
229
290
|
* Returns a {@linkcode CreatePkcs7SignedDataResult}: DER, PEM, and base64
|
|
230
291
|
* forms on success, or a typed failure for caller-correctable input (no
|
|
231
|
-
* signers, a signer source that is not exactly one certificate,
|
|
292
|
+
* signers, a signer source that is not exactly one certificate, a signer
|
|
293
|
+
* certificate whose public key cannot verify the signer key's algorithm, or an
|
|
232
294
|
* unsupported signer key).
|
|
233
295
|
*/
|
|
234
296
|
declare function createPkcs7SignedData(input: CreatePkcs7SignedDataInput): Promise<CreatePkcs7SignedDataResult>;
|
|
235
297
|
/** Parses a DER-encoded PKCS#7 cert bag, returning the contained certificates. */
|
|
236
298
|
declare function parsePkcs7CertBagDer(der: Uint8Array): ParsePkcs7CertBagResult;
|
|
237
|
-
/** Parses a PEM-armored PKCS#7 cert bag. Expects exactly one `PKCS7` PEM block. */
|
|
299
|
+
/** Parses a PEM-armored PKCS#7/CMS cert bag. Expects exactly one `PKCS7` or `CMS` PEM block. */
|
|
238
300
|
declare function parsePkcs7CertBagPem(pem: string): ParsePkcs7CertBagResult;
|
|
239
301
|
/** Decodes a DER-encoded PKCS#7 ContentInfo expecting `signedData` content type. */
|
|
240
302
|
declare function parsePkcs7SignedDataDer(der: Uint8Array): ParsePkcs7SignedDataResult;
|
|
241
|
-
/** Decodes a PEM-armored PKCS#7 SignedData. Expects exactly one `PKCS7` PEM block. */
|
|
303
|
+
/** Decodes a PEM-armored PKCS#7/CMS SignedData. Expects exactly one `PKCS7` or `CMS` PEM block. */
|
|
242
304
|
declare function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResult;
|
|
243
305
|
/**
|
|
244
306
|
* Verifies all signer signatures in a PKCS#7 SignedData structure.
|
|
@@ -258,7 +320,9 @@ declare function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResul
|
|
|
258
320
|
*
|
|
259
321
|
* const result = await verifyPkcs7SignedData(pkcs7Pem);
|
|
260
322
|
* if (result.ok) {
|
|
261
|
-
*
|
|
323
|
+
* for (const { signerInfo, certificate } of result.signers) {
|
|
324
|
+
* console.log(signerInfo.digestAlgorithmOid, certificate.subject);
|
|
325
|
+
* }
|
|
262
326
|
* }
|
|
263
327
|
*
|
|
264
328
|
* // Detached signature: supply the content externally
|
|
@@ -267,5 +331,5 @@ declare function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResul
|
|
|
267
331
|
*/
|
|
268
332
|
declare function verifyPkcs7SignedData(input: string | Uint8Array | ParsedPkcs7SignedData, options?: VerifyPkcs7SignedDataOptions): Promise<VerifyPkcs7SignedDataResult>;
|
|
269
333
|
//#endregion
|
|
270
|
-
export { CreatePkcs7CertBagErrorCode, CreatePkcs7CertBagFailure, CreatePkcs7CertBagResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, ParsedPkcs7SignerInfoBase, Pkcs7CertBagMaterial, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifyPkcs7SignedDataErrorCode, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataOptions, VerifyPkcs7SignedDataResult, createPkcs7CertBag, createPkcs7SignedData, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData };
|
|
334
|
+
export { CreatePkcs7CertBagErrorCode, CreatePkcs7CertBagFailure, CreatePkcs7CertBagResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedCertificateChoice, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, ParsedPkcs7SignerInfoBase, ParsedSignerIdentifier, Pkcs7CertBagMaterial, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifiedPkcs7Signer, VerifyPkcs7SignedDataErrorCode, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataOptions, VerifyPkcs7SignedDataResult, createPkcs7CertBag, createPkcs7SignedData, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData };
|
|
271
335
|
//# sourceMappingURL=pkcs7.d.ts.map
|