micro509 0.5.0 → 0.7.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 +6 -6
- package/dist/index.d.ts +13 -14
- package/dist/index.js +1 -1
- package/dist/internal/crypto/pbes2.d.ts +6 -6
- package/dist/internal/crypto/pbes2.js +1 -1
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +1 -1
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/keys/keys.d.ts +15 -15
- package/dist/keys/keys.js +1 -1
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +2 -3
- package/dist/pem/pem.d.ts +57 -6
- package/dist/pem/pem.js +5 -5
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +2 -2
- package/dist/pem.js +1 -1
- package/dist/pkcs/pfx.d.ts +4 -4
- package/dist/pkcs/pfx.js +1 -1
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +29 -5
- package/dist/pkcs/pkcs12-mac.js +1 -1
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +36 -50
- package/dist/pkcs/pkcs7.js +1 -1
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +3 -4
- package/dist/pkcs.js +1 -1
- package/dist/result/result.d.ts +3 -12
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +2 -2
- package/dist/result.js +1 -1
- package/dist/revocation/chain.d.ts +35 -34
- package/dist/revocation/chain.js +1 -1
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +40 -15
- package/dist/revocation/crl.js +1 -1
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +63 -13
- package/dist/revocation/ocsp.js +1 -1
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +21 -19
- package/dist/revocation/revocation.js +1 -1
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +7 -5
- package/dist/revocation.js +1 -1
- package/dist/verify/identity.d.ts +4 -10
- package/dist/verify/identity.js +1 -1
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/verify.d.ts +9 -9
- package/dist/verify/verify.js +1 -1
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -2
- package/dist/x509/certificate.d.ts +2 -2
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +2 -2
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +21 -6
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/parse.d.ts +3 -4
- package/dist/x509/parse.js +1 -1
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +3 -4
- package/package.json +3 -1
- package/dist/internal/x509/extension-bits.d.ts +0 -18
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.ts';\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/**\n * Extracts and base64-decodes the DER content from a PEM string.\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 pemDecode(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 splitPemBlocks(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: pemDecode(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 categorizePemBlocks(input: string | readonly PemBlock[]): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocks(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"],"mappings":"8EA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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.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\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\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":"6KAmDA,SAAgB,EAAU,EAAe,EAAyB,CAGjE,MAAO,cAAc,EAAM,UAFd,EAAa,CACT,CAAC,CAAC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CACnE,OAAO,MAAkB,EAAsB,CAAK,EAAG,qBAAqB,CAC7E,CAWA,SAAgB,EACf,EAC4B,CAC5B,OAAO,MAAkB,EAA2B,CAAK,EAAG,qBAAqB,CAClF,CAGA,SAAS,EACR,EACA,EAG8D,CAC9D,GAAI,CACH,OAAO,EAAc,EAAU,CAAC,CACjC,OAAS,EAAO,CAEf,OADA,EAAmB,CAAK,EACjB,EAAc,YAAa,aAAiB,MAAQ,EAAM,QAAU,CAAe,CAC3F,CACD"}
|
package/dist/pem.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { CategorizedPemBlocks, PemBlock, categorizePemBlocks, pemDecode, pemEncode, splitPemBlocks } from "./pem/pem.js";
|
|
2
|
-
export { type CategorizedPemBlocks, type PemBlock, categorizePemBlocks, pemDecode, pemEncode, splitPemBlocks };
|
|
1
|
+
import { CategorizePemBlocksResult, CategorizedPemBlocks, PemBlock, PemDecodeResult, PemErrorCode, PemFailure, SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow } from "./pem/pem.js";
|
|
2
|
+
export { type CategorizePemBlocksResult, type CategorizedPemBlocks, type PemBlock, type PemDecodeResult, type PemErrorCode, type PemFailure, type SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
|
package/dist/pem.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{categorizePemBlocks as e,
|
|
1
|
+
import{categorizePemBlocks as e,categorizePemBlocksOrThrow as t,pemDecode as n,pemDecodeOrThrow as r,pemEncode as i,splitPemBlocks as a,splitPemBlocksOrThrow as o}from"./pem/pem.js";export{e as categorizePemBlocks,t as categorizePemBlocksOrThrow,n as pemDecode,r as pemDecodeOrThrow,i as pemEncode,a as splitPemBlocks,o as splitPemBlocksOrThrow};
|
package/dist/pkcs/pfx.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { Pbes2EncryptionOptions
|
|
1
|
+
import { Pbes2EncryptionOptions } from "../internal/crypto/pbes2.js";
|
|
2
2
|
import { ErrorResult, Micro509Error } from "../result/result.js";
|
|
3
3
|
import { ParsedCertificate } from "../x509/parse.js";
|
|
4
|
-
import { ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData } from "./pkcs12-mac.js";
|
|
4
|
+
import { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow } from "./pkcs12-mac.js";
|
|
5
5
|
|
|
6
6
|
//#region src/pkcs/pfx.d.ts
|
|
7
7
|
/** PEM string or DER bytes for a certificate to include in a PFX bag. */
|
|
8
|
-
type PfxCertificateSource = string | Uint8Array;
|
|
8
|
+
type PfxCertificateSource = string | Uint8Array | ParsedCertificate;
|
|
9
9
|
/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */
|
|
10
10
|
type PfxPrivateKeySource = CryptoKey | Uint8Array;
|
|
11
11
|
/** Optional metadata attached to a certificate or key bag inside a PFX. */
|
|
@@ -199,5 +199,5 @@ declare function parsePfxDer(der: Uint8Array, options?: ParsePfxOptions): Promis
|
|
|
199
199
|
*/
|
|
200
200
|
declare function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult>;
|
|
201
201
|
//#endregion
|
|
202
|
-
export { CreatePfxErrorCode, CreatePfxFailure, CreatePfxInput, CreatePfxResult, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult,
|
|
202
|
+
export { CreatePfxErrorCode, CreatePfxFailure, CreatePfxInput, CreatePfxResult, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult, type ParsePkcs12MacDataErrorCode, type ParsePkcs12MacDataFailure, type ParsePkcs12MacDataResult, ParsedPfx, ParsedPfxAttribute, ParsedPfxBag, ParsedPfxBagAttributes, type ParsedPkcs12MacData, PfxBagAttributesInput, PfxCertificateBagInput, PfxCertificateSource, PfxEncryptionOptions, PfxMaterial, PfxPrivateKeyBagInput, PfxPrivateKeySource, type Pkcs12MacOptions, createPfx, type createPkcs12MacData, parsePfxDer, parsePfxPem, type parsePkcs12MacData, type parsePkcs12MacDataOrThrow };
|
|
203
203
|
//# sourceMappingURL=pfx.d.ts.map
|
package/dist/pkcs/pfx.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{explicitContext as e,integerFromNumber as t,objectIdentifier as n,octetString as r,readElement as i,readSequenceChildren as a,sequence as o,setOf as s,tlv as c}from"../internal/asn1/der.js";import{childrenOf as l,decodeIntegerNumber as u,decodeObjectIdentifier as d,toHex as f}from"../internal/asn1/asn1.js";import{OIDS as p}from"../internal/asn1/oids.js";import{decryptPbes2 as m,encryptPbes2 as h}from"../internal/crypto/pbes2.js";import{base64Encode as g}from"../internal/shared/base64.js";import{
|
|
1
|
+
import{explicitContext as e,integerFromNumber as t,objectIdentifier as n,octetString as r,readElement as i,readSequenceChildren as a,sequence as o,setOf as s,tlv as c}from"../internal/asn1/der.js";import{childrenOf as l,decodeIntegerNumber as u,decodeObjectIdentifier as d,toHex as f}from"../internal/asn1/asn1.js";import{OIDS as p}from"../internal/asn1/oids.js";import{decryptPbes2 as m,encryptPbes2 as h}from"../internal/crypto/pbes2.js";import{base64Encode as g}from"../internal/shared/base64.js";import{failureResult as _}from"../result/result.js";import{pemEncode as v,splitPemBlocksOrThrow as y}from"../pem/pem.js";import{exportPkcs8Der as b}from"../keys/keys.js";import{parseCertificateDerOrThrow as x}from"../x509/parse.js";import{createPkcs12MacData as S,parsePkcs12MacData as C}from"./pkcs12-mac.js";async function w(e){let n=[],r=[];for(let t of e.certificates??[]){let e;try{e=V(t.certificate)}catch{return T(`invalid_certificate`,`Each PFX certificate source must be a single PEM or DER certificate`)}n.push(j(e,t.attributes))}for(let t of e.privateKeys??[])r.push(M(await B(t.privateKey),t.attributes));let i=[];if(n.length>0&&i.push(N(o(n))),r.length>0){let t=o(r);i.push(e.encryption===void 0?N(t):await P(t,e.encryption))}let a=o(i),s=e.mac===void 0?void 0:await S(a,e.mac),c=o([t(3),N(a),...s===void 0?[]:[s.der]]);return{ok:!0,value:{der:c,pem:v(`PKCS12`,c),base64:g(c)}}}function T(e,t){return _(e,t)}async function E(e,t){try{let n=a(e,{maxDepth:64});if(n.length<2||n.length>3)return O(`malformed`,`Malformed PFX structure`);let r=n[0],i=n[1];if(r===void 0||i===void 0||r.tag!==2)return O(`malformed`,`Malformed PFX structure`);if(u(r.value)!==3)return O(`malformed`,`Unsupported PFX version`);let o=k(e.slice(i.start-i.headerLength,i.end)),s=n[2],c;if(s!==void 0){let n=await C(e.slice(s.start-s.headerLength,s.end),o,t?.macPassword??t?.password);if(!n.ok)return O(`malformed`,`Malformed PFX MacData`);if(c=n.value,c.verification===`invalid`)return O(`invalid_password`,`Invalid PFX MAC password or corrupted content`)}let l=a(o),d=[];for(let e of l){let n=await A(o.slice(e.start-e.headerLength,e.end),t);if(n.error!==void 0)return n.error;let r=n.data;for(let e of a(r)){let t=r.slice(e.start-e.headerLength,e.end);d.push(I(t))}}return{ok:!0,value:{bags:d,certificates:d.flatMap(e=>e.kind===`certificate`?[e.certificate]:[]),privateKeys:d.flatMap(e=>e.kind===`privateKey`?[e.pkcs8Der]:[]),...c===void 0?{}:{macData:c}}}}catch{return O(`malformed`,`Malformed PFX structure`)}}async function D(e,t){try{let n=y(e).filter(e=>e.label===`PKCS12`),r=n[0];return r===void 0||n.length!==1?O(`malformed`,`Expected exactly one PKCS12 PEM block`):E(r.bytes,t)}catch{return O(`malformed`,`Expected exactly one PKCS12 PEM block`)}}function O(e,t){return _(e,t)}function k(e){let t=a(e),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2||n.tag!==6)throw Error(`Malformed ContentInfo`);if(d(n.value)!==p.pkcs7Data)throw Error(`Only passwordless data ContentInfo is supported`);return U(e,r)}async function A(e,t){let n=a(e),r=n[0],i=n[1];if(r===void 0||i===void 0||n.length!==2||r.tag!==6)return{error:O(`malformed`,`Malformed ContentInfo`)};let o=d(r.value);if(o===p.pkcs7Data)return{data:U(e,i)};if(o!==p.pkcs7EncryptedData)return{error:O(`malformed`,`Unsupported PFX ContentInfo type`)};if(t?.password===void 0)return{error:O(`password_required`,`Password required for encrypted PFX content`)};let s=W(e,i);try{let n=await H(e.slice(s.start-s.headerLength,s.end),t.password);return a(n),{data:n}}catch(e){return z(e)?{error:O(`malformed`,`Malformed PFX encrypted content`)}:{error:O(`invalid_password`,`Invalid PFX password or encrypted content`)}}}function j(t,i){let a=o([n(p.x509CertificateBagType),e(0,r(t))]);return o([n(p.pkcs12CertBag),e(0,a),...F(i)])}function M(t,r){return o([n(p.pkcs12KeyBag),e(0,t),...F(r)])}function N(t){return o([n(p.pkcs7Data),e(0,r(t))])}async function P(r,i){let a=await h(r,i),s=o([t(0),o([n(p.pkcs7Data),a.algorithmIdentifierDer,c(128,a.encryptedData)])]);return o([n(p.pkcs7EncryptedData),e(0,s)])}function F(e){if(e===void 0)return[];let t=[];return e.friendlyName!==void 0&&t.push(o([n(p.friendlyName),s([G(e.friendlyName)])])),e.localKeyId!==void 0&&t.push(o([n(p.localKeyId),s([r(e.localKeyId)])])),t.length===0?[]:[s(t)]}function I(e){let t=a(e),n=t[0],r=t[1],i=t[2];if(n===void 0||r===void 0||t.length>3)throw Error(`Malformed SafeBag`);let o=d(n.value),s=L(e,i);if(o===p.pkcs12CertBag){let t=W(e,r),n=e.slice(t.start-t.headerLength,t.end),i=a(n),c=i[0],l=i[1];if(c===void 0||l===void 0||i.length!==2||d(c.value)!==p.x509CertificateBagType)throw Error(`Malformed certBag`);return{kind:`certificate`,bagId:o,attributes:s,certificate:x(U(n,l))}}if(o===p.pkcs12KeyBag){let t=W(e,r);return{kind:`privateKey`,bagId:o,attributes:s,pkcs8Der:e.slice(t.start-t.headerLength,t.end)}}let c=W(e,r);return{kind:`unknown`,bagId:o,attributes:s,valueDer:e.slice(c.start-c.headerLength,c.end)}}function L(e,t){if(t===void 0)return{entries:[]};let n=[],r,i;for(let o of l(e,t)){let t=e.slice(o.start-o.headerLength,o.end),s=a(t),c=s[0],u=s[1];if(c===void 0||u===void 0||s.length!==2||u.tag!==49)throw Error(`Malformed PFX bag attribute`);let m=d(c.value),h=l(t,u).map(e=>t.slice(e.start-e.headerLength,e.end));if(n.push({oid:m,valuesHex:h.map(e=>f(e))}),m===p.friendlyName){let e=h[0];if(r!==void 0||h.length!==1||e===void 0)throw Error(`Malformed friendlyName attribute`);r=K(e);continue}if(m===p.localKeyId){let e=h[0];if(i!==void 0||h.length!==1||e===void 0)throw Error(`Malformed localKeyId attribute`);i=R(e)}}return{entries:n,...r===void 0?{}:{friendlyName:r},...i===void 0?{}:{localKeyId:i}}}function R(e){let t=i(e);if(t.tag!==4)throw Error(`localKeyId must use OCTET STRING`);return f(t.value)}function z(e){return e instanceof Error?e.message.startsWith(`Malformed `)||e.message.startsWith(`Unsupported `)||e.message.startsWith(`Invalid PBES2 `)||e.message===`Only passwordless data ContentInfo is supported`:!1}async function B(e){return e instanceof CryptoKey?b(e):new Uint8Array(e)}function V(e){if(typeof e==`string`){let t=y(e).find(e=>e.label===`CERTIFICATE`);if(t===void 0)throw Error(`Certificate PEM required`);return new Uint8Array(t.bytes)}return e instanceof Uint8Array?new Uint8Array(e):new Uint8Array(e.der)}async function H(e,t){let n=a(e),r=n[1];if(n.length!==2||r===void 0)throw Error(`Malformed EncryptedData`);let i=n[0];if(i===void 0||i.tag!==2||u(i.value)!==0)throw Error(`Malformed EncryptedData`);let o=e.slice(r.start-r.headerLength,r.end),s=a(o),c=s[1],l=s[2];if(c===void 0||l===void 0||s.length!==3||s[0]?.tag!==6)throw Error(`Malformed EncryptedContentInfo`);if(l.tag!==128)throw Error(`Malformed encrypted content`);return m(o.slice(c.start-c.headerLength,c.end),l.value,t)}function U(e,t){let n=W(e,t);if(n.tag!==4)throw Error(`Expected OCTET STRING in context value`);return n.value}function W(e,t){if((t.tag&224)!=160)throw Error(`Expected context-specific constructed value`);let n=l(e,t),r=n[0];if(n.length!==1||r===void 0)throw Error(`Expected context-specific wrapper with exactly one value`);return r}function G(e){let t=new Uint8Array(e.length*2);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);t[n*2]=r>>8,t[n*2+1]=r&255}return c(30,t)}function K(e){let t=i(e);if(t.tag!==30)throw Error(`Expected BMPString`);if(t.value.length%2!=0)throw Error(`BMPString must use an even number of bytes`);let n=``;for(let e=0;e<t.value.length;e+=2){let r=t.value[e]??0,i=t.value[e+1]??0;n+=String.fromCharCode(r<<8|i)}return n}export{w as createPfx,E as parsePfxDer,D as parsePfxPem};
|
|
2
2
|
//# sourceMappingURL=pfx.js.map
|
package/dist/pkcs/pfx.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pfx.js","names":[],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\ttype Pbes2EncryptionOptions,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { exportPkcs8Der } from '#micro509/keys/keys.ts';\nimport { pemEncode, splitPemBlocks } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\nexport type * from './pkcs12-mac.ts';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/** Human-readable label stored as a BMPString attribute. */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode Pbes2EncryptionOptions}. */\nexport type PfxEncryptionOptions = Pbes2EncryptionOptions;\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/** Hex-encoded DER of each attribute value. */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER of the unrecognized bag value. */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PFX parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode = 'malformed' | 'invalid_password' | 'password_required';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// Result types for PFX creation\n// ---------------------------------------------------------------------------\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// createPfx\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// ---------------------------------------------------------------------------\n// parsePfxDer / parsePfxPem — Result-returning\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined || version.tag !== 0x02) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(version.value) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authSafeDer = der.slice(authSafe.start - authSafe.headerLength, authSafe.end);\n\t\tconst authenticatedSafeOctets = extractContentInfoData(authSafeDer);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\ttry {\n\t\t\t\tmacData = await parsePkcs12MacData(\n\t\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tif (macData?.valid === false) {\n\t\t\t\treturn pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content');\n\t\t\t}\n\t\t}\n\t\tconst authenticatedSafe = readSequenceChildren(authenticatedSafeOctets);\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of authenticatedSafe) {\n\t\t\tconst contentInfoDer = authenticatedSafeOctets.slice(\n\t\t\t\tcontentInfo.start - contentInfo.headerLength,\n\t\t\t\tcontentInfo.end,\n\t\t\t);\n\t\t\tconst safeContentsResult = await extractSafeContents(contentInfoDer, options);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of readSequenceChildren(safeContents)) {\n\t\t\t\tconst bagDer = safeContents.slice(bag.start - bag.headerLength, bag.end);\n\t\t\t\tbags.push(parseSafeBag(bagDer));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst blocks = splitPemBlocks(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\treturn parsePfxDer(block.bytes, options);\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Private: PFX helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(contentInfoDer: Uint8Array): Uint8Array {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\tif (decodeObjectIdentifier(contentType.value) !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(contentInfoDer, content);\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tcontentInfoDer: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\treturn { error: pfxFailure('malformed', 'Malformed ContentInfo') };\n\t}\n\tconst oid = decodeObjectIdentifier(contentType.value);\n\tif (oid === OIDS.pkcs7Data) {\n\t\treturn { data: extractContextOctetString(contentInfoDer, content) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(contentInfoDer, content);\n\ttry {\n\t\tconst decrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t\treadSequenceChildren(decrypted);\n\t\treturn { data: decrypted };\n\t} catch (error) {\n\t\tif (isMalformedPfxEncryptedContentError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.friendlyName), setOf([bmpString(attributes.friendlyName)])]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** Decodes a single SafeBag from DER into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(der: Uint8Array): ParsedPfxBag {\n\tconst children = readSequenceChildren(der);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(bagId.value);\n\tconst attributes = parseBagAttributes(der, attributeSet);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBag = extractContextChild(der, bagValue);\n\t\tconst certBagDer = der.slice(certBag.start - certBag.headerLength, certBag.end);\n\t\tconst certBagChildren = readSequenceChildren(certBagDer);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(certType.value) !== OIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\tconst certificateDer = extractContextOctetString(certBagDer, certValue);\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(certificateDer),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8 = extractContextChild(der, bagValue);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der: der.slice(pkcs8.start - pkcs8.headerLength, pkcs8.end),\n\t\t};\n\t}\n\tconst value = extractContextChild(der, bagValue);\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: der.slice(value.start - value.headerLength, value.end),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: DerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of childrenOf(source, attributeSet)) {\n\t\tconst attributeDer = source.slice(attribute.start - attribute.headerLength, attribute.end);\n\t\tconst parts = readSequenceChildren(attributeDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst rawValues = childrenOf(attributeDer, values).map((value) =>\n\t\t\tattributeDer.slice(value.start - value.headerLength, value.end),\n\t\t);\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeBmpString(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\nfunction isMalformedPfxEncryptedContentError(error: unknown): boolean {\n\tif (!(error instanceof Error)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\terror.message.startsWith('Malformed ') ||\n\t\terror.message.startsWith('Unsupported ') ||\n\t\terror.message.startsWith('Invalid PBES2 ') ||\n\t\terror.message === 'Only passwordless data ContentInfo is supported'\n\t);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nasync function normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\tif (source instanceof CryptoKey) {\n\t\treturn exportPkcs8Der(source);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocks(source).find((candidate) => candidate.label === 'CERTIFICATE');\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nasync function decryptEncryptedData(\n\tencryptedDataDer: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst topLevel = readSequenceChildren(encryptedDataDer);\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst version = topLevel[0];\n\tif (version === undefined || version.tag !== 0x02 || decodeIntegerNumber(version.value) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoDer = encryptedDataDer.slice(\n\t\tencryptedContentInfo.start - encryptedContentInfo.headerLength,\n\t\tencryptedContentInfo.end,\n\t);\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3 ||\n\t\tcontentInfoChildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tif (encryptedContent.tag !== 0x80) {\n\t\tthrow new Error('Malformed encrypted content');\n\t}\n\treturn decryptPbes2(\n\t\tcontentInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\tencryptedContent.value,\n\t\tpassword,\n\t);\n}\n\n/** Reads the first child of a context-tagged element, expecting an OCTET STRING. */\nfunction extractContextOctetString(source: Uint8Array, element: DerElement): Uint8Array {\n\tconst child = extractContextChild(source, element);\n\tif (child.tag !== 0x04) {\n\t\tthrow new Error('Expected OCTET STRING in context value');\n\t}\n\treturn child.value;\n}\n\n/** Reads the first child element inside a context-specific constructed wrapper. */\nfunction extractContextChild(source: Uint8Array, element: DerElement): DerElement {\n\tif ((element.tag & 0xe0) !== 0xa0) {\n\t\tthrow new Error('Expected context-specific constructed value');\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** Encodes a JS string as an ASN.1 BMPString (UCS-2 big-endian, tag 0x1e). */\nfunction bmpString(value: string): Uint8Array {\n\tconst bytes = new Uint8Array(value.length * 2);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst codePoint = value.charCodeAt(index);\n\t\tbytes[index * 2] = codePoint >> 8;\n\t\tbytes[index * 2 + 1] = codePoint & 0xff;\n\t}\n\treturn tlv(0x1e, bytes);\n}\n\n/** Decodes a DER-encoded BMPString (tag 0x1e) back to a JS string. */\nfunction decodeBmpString(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('Expected BMPString');\n\t}\n\tif (element.value.length % 2 !== 0) {\n\t\tthrow new Error('BMPString must use an even number of bytes');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < element.value.length; index += 2) {\n\t\tconst left = element.value[index] ?? 0;\n\t\tconst right = element.value[index + 1] ?? 0;\n\t\tvalue += String.fromCharCode((left << 8) | right);\n\t}\n\treturn value;\n}\n"],"mappings":"myBAyQA,eAAsB,EAAU,EAAiD,CAChF,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAAG,CAGnD,IAAI,EACJ,GAAI,CACH,EAAiB,EAAqB,EAAY,WAAW,CAC9D,MAAQ,CACP,OAAO,EACN,sBACA,qEACD,CACD,CACA,EAAgB,KAAK,EAAqB,EAAgB,EAAY,UAAU,CAAC,CAClF,CACA,IAAK,IAAM,KAAc,EAAM,aAAe,CAAC,EAC9C,EAAe,KACd,EAAoB,MAAM,EAAoB,EAAW,UAAU,EAAG,EAAW,UAAU,CAC5F,EAED,IAAM,EAA6B,CAAC,EAIpC,GAHI,EAAgB,OAAS,GAC5B,EAAa,KAAK,EAAsB,EAAS,CAAe,CAAC,CAAC,EAE/D,EAAe,OAAS,EAAG,CAC9B,IAAM,EAAe,EAAS,CAAc,EAC5C,EAAa,KACZ,EAAM,aAAe,IAAA,GAClB,EAAsB,CAAY,EAClC,MAAM,EAA+B,EAAc,EAAM,UAAU,CACvE,CACD,CACA,IAAM,EAAoB,EAAS,CAAY,EACzC,EACL,EAAM,MAAQ,I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AAM,OAAS,CAAC,EAC7C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAY,EAAM,WAAW,CAAK,EACxC,EAAM,EAAQ,GAAK,GAAa,EAChC,EAAM,EAAQ,EAAI,GAAK,EAAY,GACpC,CACA,OAAO,EAAI,GAAM,CAAK,CACvB,CAGA,SAAS,EAAgB,EAAyB,CACjD,IAAM,EAAU,EAAY,CAAG,EAC/B,GAAI,EAAQ,MAAQ,GACnB,MAAU,MAAM,oBAAoB,EAErC,GAAI,EAAQ,MAAM,OAAS,GAAM,EAChC,MAAU,MAAM,4CAA4C,EAE7D,IAAI,EAAQ,GACZ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,MAAM,OAAQ,GAAS,EAAG,CAC7D,IAAM,EAAO,EAAQ,MAAM,IAAU,EAC/B,EAAQ,EAAQ,MAAM,EAAQ,IAAM,EAC1C,GAAS,OAAO,aAAc,GAAQ,EAAK,CAAK,CACjD,CACA,OAAO,CACR"}
|
|
1
|
+
{"version":3,"file":"pfx.js","names":[],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\ttype Pbes2EncryptionOptions,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { exportPkcs8Der } from '#micro509/keys/keys.ts';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type * from './pkcs12-mac.ts';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/** Human-readable label stored as a BMPString attribute. */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode Pbes2EncryptionOptions}. */\nexport type PfxEncryptionOptions = Pbes2EncryptionOptions;\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/** Hex-encoded DER of each attribute value. */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER of the unrecognized bag value. */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PFX parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode = 'malformed' | 'invalid_password' | 'password_required';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// Result types for PFX creation\n// ---------------------------------------------------------------------------\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// createPfx\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// ---------------------------------------------------------------------------\n// parsePfxDer / parsePfxPem — Result-returning\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined || version.tag !== 0x02) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(version.value) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authSafeDer = der.slice(authSafe.start - authSafe.headerLength, authSafe.end);\n\t\tconst authenticatedSafeOctets = extractContentInfoData(authSafeDer);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await parsePkcs12MacData(\n\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t);\n\t\t\tif (!macResult.ok) {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tmacData = macResult.value;\n\t\t\tif (macData.verification === 'invalid') {\n\t\t\t\treturn pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content');\n\t\t\t}\n\t\t}\n\t\tconst authenticatedSafe = readSequenceChildren(authenticatedSafeOctets);\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of authenticatedSafe) {\n\t\t\tconst contentInfoDer = authenticatedSafeOctets.slice(\n\t\t\t\tcontentInfo.start - contentInfo.headerLength,\n\t\t\t\tcontentInfo.end,\n\t\t\t);\n\t\t\tconst safeContentsResult = await extractSafeContents(contentInfoDer, options);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of readSequenceChildren(safeContents)) {\n\t\t\t\tconst bagDer = safeContents.slice(bag.start - bag.headerLength, bag.end);\n\t\t\t\tbags.push(parseSafeBag(bagDer));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\treturn parsePfxDer(block.bytes, options);\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Private: PFX helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(contentInfoDer: Uint8Array): Uint8Array {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\tif (decodeObjectIdentifier(contentType.value) !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(contentInfoDer, content);\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tcontentInfoDer: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\treturn { error: pfxFailure('malformed', 'Malformed ContentInfo') };\n\t}\n\tconst oid = decodeObjectIdentifier(contentType.value);\n\tif (oid === OIDS.pkcs7Data) {\n\t\treturn { data: extractContextOctetString(contentInfoDer, content) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(contentInfoDer, content);\n\ttry {\n\t\tconst decrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t\treadSequenceChildren(decrypted);\n\t\treturn { data: decrypted };\n\t} catch (error) {\n\t\tif (isMalformedPfxEncryptedContentError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.friendlyName), setOf([bmpString(attributes.friendlyName)])]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** Decodes a single SafeBag from DER into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(der: Uint8Array): ParsedPfxBag {\n\tconst children = readSequenceChildren(der);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(bagId.value);\n\tconst attributes = parseBagAttributes(der, attributeSet);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBag = extractContextChild(der, bagValue);\n\t\tconst certBagDer = der.slice(certBag.start - certBag.headerLength, certBag.end);\n\t\tconst certBagChildren = readSequenceChildren(certBagDer);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(certType.value) !== OIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\tconst certificateDer = extractContextOctetString(certBagDer, certValue);\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(certificateDer),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8 = extractContextChild(der, bagValue);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der: der.slice(pkcs8.start - pkcs8.headerLength, pkcs8.end),\n\t\t};\n\t}\n\tconst value = extractContextChild(der, bagValue);\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: der.slice(value.start - value.headerLength, value.end),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: DerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of childrenOf(source, attributeSet)) {\n\t\tconst attributeDer = source.slice(attribute.start - attribute.headerLength, attribute.end);\n\t\tconst parts = readSequenceChildren(attributeDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst rawValues = childrenOf(attributeDer, values).map((value) =>\n\t\t\tattributeDer.slice(value.start - value.headerLength, value.end),\n\t\t);\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeBmpString(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\nfunction isMalformedPfxEncryptedContentError(error: unknown): boolean {\n\tif (!(error instanceof Error)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\terror.message.startsWith('Malformed ') ||\n\t\terror.message.startsWith('Unsupported ') ||\n\t\terror.message.startsWith('Invalid PBES2 ') ||\n\t\terror.message === 'Only passwordless data ContentInfo is supported'\n\t);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nasync function normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\tif (source instanceof CryptoKey) {\n\t\treturn exportPkcs8Der(source);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nasync function decryptEncryptedData(\n\tencryptedDataDer: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst topLevel = readSequenceChildren(encryptedDataDer);\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst version = topLevel[0];\n\tif (version === undefined || version.tag !== 0x02 || decodeIntegerNumber(version.value) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoDer = encryptedDataDer.slice(\n\t\tencryptedContentInfo.start - encryptedContentInfo.headerLength,\n\t\tencryptedContentInfo.end,\n\t);\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3 ||\n\t\tcontentInfoChildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tif (encryptedContent.tag !== 0x80) {\n\t\tthrow new Error('Malformed encrypted content');\n\t}\n\treturn decryptPbes2(\n\t\tcontentInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\tencryptedContent.value,\n\t\tpassword,\n\t);\n}\n\n/** Reads the first child of a context-tagged element, expecting an OCTET STRING. */\nfunction extractContextOctetString(source: Uint8Array, element: DerElement): Uint8Array {\n\tconst child = extractContextChild(source, element);\n\tif (child.tag !== 0x04) {\n\t\tthrow new Error('Expected OCTET STRING in context value');\n\t}\n\treturn child.value;\n}\n\n/** Reads the first child element inside a context-specific constructed wrapper. */\nfunction extractContextChild(source: Uint8Array, element: DerElement): DerElement {\n\tif ((element.tag & 0xe0) !== 0xa0) {\n\t\tthrow new Error('Expected context-specific constructed value');\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** Encodes a JS string as an ASN.1 BMPString (UCS-2 big-endian, tag 0x1e). */\nfunction bmpString(value: string): Uint8Array {\n\tconst bytes = new Uint8Array(value.length * 2);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst codePoint = value.charCodeAt(index);\n\t\tbytes[index * 2] = codePoint >> 8;\n\t\tbytes[index * 2 + 1] = codePoint & 0xff;\n\t}\n\treturn tlv(0x1e, bytes);\n}\n\n/** Decodes a DER-encoded BMPString (tag 0x1e) back to a JS string. */\nfunction decodeBmpString(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('Expected BMPString');\n\t}\n\tif (element.value.length % 2 !== 0) {\n\t\tthrow new Error('BMPString must use an even number of bytes');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < element.value.length; index += 2) {\n\t\tconst left = element.value[index] ?? 0;\n\t\tconst right = element.value[index + 1] ?? 0;\n\t\tvalue += String.fromCharCode((left << 8) | right);\n\t}\n\treturn value;\n}\n"],"mappings":"0yBAoQA,eAAsB,EAAU,EAAiD,CAChF,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAAG,CAGnD,IAAI,EACJ,GAAI,CACH,EAAiB,EAAqB,EAAY,WAAW,CAC9D,MAAQ,CACP,OAAO,EACN,sBACA,qEACD,CACD,CACA,EAAgB,KAAK,EAAqB,EAAgB,EAAY,UAAU,CAAC,CAClF,CACA,IAAK,IAAM,KAAc,EAAM,aAAe,CAAC,EAC9C,EAAe,KACd,EAAoB,MAAM,EAAoB,EAAW,UAAU,EAAG,EAAW,UAAU,CAC5F,EAED,IAAM,EAA6B,CAAC,EAIpC,GAHI,EAAgB,OAAS,GAC5B,EAAa,KAAK,EAAsB,EAAS,CAAe,CAAC,CAAC,EAE/D,EAAe,OAAS,EAAG,CAC9B,IAAM,EAAe,EAAS,CAAc,EAC5C,EAAa,KACZ,EAAM,aAAe,IAAA,GAClB,EAAsB,CAAY,EAClC,MAAM,EAA+B,EAAc,EAAM,UAAU,CACvE,CACD,CAC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,GAAK,IAAU,IAAA,GACtC,MAAU,MAAM,0DAA0D,EAE3E,OAAO,CACR,CAGA,SAAS,EAAU,EAA2B,CAC7C,IAAM,EAAQ,IAAI,WAAW,EAAM,OAAS,CAAC,EAC7C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAY,EAAM,WAAW,CAAK,EACxC,EAAM,EAAQ,GAAK,GAAa,EAChC,EAAM,EAAQ,EAAI,GAAK,EAAY,GACpC,CACA,OAAO,EAAI,GAAM,CAAK,CACvB,CAGA,SAAS,EAAgB,EAAyB,CACjD,IAAM,EAAU,EAAY,CAAG,EAC/B,GAAI,EAAQ,MAAQ,GACnB,MAAU,MAAM,oBAAoB,EAErC,GAAI,EAAQ,MAAM,OAAS,GAAM,EAChC,MAAU,MAAM,4CAA4C,EAE7D,IAAI,EAAQ,GACZ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,MAAM,OAAQ,GAAS,EAAG,CAC7D,IAAM,EAAO,EAAQ,MAAM,IAAU,EAC/B,EAAQ,EAAQ,MAAM,EAAQ,IAAM,EAC1C,GAAS,OAAO,aAAc,GAAQ,EAAK,CAAK,CACjD,CACA,OAAO,CACR"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ErrorResult, Micro509Error } from "../result/result.js";
|
|
2
|
+
|
|
1
3
|
//#region src/pkcs/pkcs12-mac.d.ts
|
|
2
4
|
/** Input for {@linkcode createPkcs12MacData}. */
|
|
3
5
|
interface Pkcs12MacOptions {
|
|
@@ -20,8 +22,11 @@ interface ParsedPkcs12MacData {
|
|
|
20
22
|
readonly saltHex: string;
|
|
21
23
|
/** Number of PKCS#12 KDF iterations. */
|
|
22
24
|
readonly iterations: number;
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
+
/**
|
|
26
|
+
* MAC verification outcome: `'unchecked'` when no password was supplied
|
|
27
|
+
* during parsing, otherwise `'valid'` or `'invalid'`.
|
|
28
|
+
*/
|
|
29
|
+
readonly verification: "valid" | "invalid" | "unchecked";
|
|
25
30
|
}
|
|
26
31
|
/**
|
|
27
32
|
* Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns
|
|
@@ -31,11 +36,30 @@ declare function createPkcs12MacData(authenticatedSafe: Uint8Array, options: Pkc
|
|
|
31
36
|
/** DER-encoded MacData SEQUENCE. */readonly der: Uint8Array; /** Structured representation of the MAC parameters and digest. */
|
|
32
37
|
readonly parsed: ParsedPkcs12MacData;
|
|
33
38
|
}>;
|
|
39
|
+
/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */
|
|
40
|
+
type ParsePkcs12MacDataErrorCode = "malformed";
|
|
41
|
+
/** Structured failure payload for MacData parsing. */
|
|
42
|
+
interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {
|
|
43
|
+
readonly ok: false;
|
|
44
|
+
}
|
|
45
|
+
/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */
|
|
46
|
+
type ParsePkcs12MacDataResult = {
|
|
47
|
+
readonly ok: true;
|
|
48
|
+
readonly value: ParsedPkcs12MacData;
|
|
49
|
+
} | ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;
|
|
50
|
+
/**
|
|
51
|
+
* Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
|
|
52
|
+
* provided, verifies the MAC and reports the outcome in `verification`.
|
|
53
|
+
*/
|
|
54
|
+
declare function parsePkcs12MacDataOrThrow(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsedPkcs12MacData>;
|
|
34
55
|
/**
|
|
35
56
|
* Decodes a DER-encoded MacData block. When `password` is provided, verifies
|
|
36
|
-
* the MAC and
|
|
57
|
+
* the MAC and reports the outcome in `verification`.
|
|
58
|
+
*
|
|
59
|
+
* Returns a typed failure (`code: 'malformed'`) on malformed input. For the
|
|
60
|
+
* throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
|
|
37
61
|
*/
|
|
38
|
-
declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<
|
|
62
|
+
declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsePkcs12MacDataResult>;
|
|
39
63
|
//#endregion
|
|
40
|
-
export { ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData };
|
|
64
|
+
export { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
|
|
41
65
|
//# sourceMappingURL=pkcs12-mac.d.ts.map
|
package/dist/pkcs/pkcs12-mac.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{concatBytes as e,integerFromNumber as t,nullValue as n,objectIdentifier as r,octetString as i,readSequenceChildren as a,sequence as o}from"../internal/asn1/der.js";import{decodeNonNegativeIntegerNumber as s,decodeObjectIdentifier as c,toArrayBuffer as l,toHex as u}from"../internal/asn1/asn1.js";import{OIDS as d}from"../internal/asn1/oids.js";import{getCrypto as f}from"../internal/crypto/webcrypto.js";import{
|
|
1
|
+
import{concatBytes as e,integerFromNumber as t,nullValue as n,objectIdentifier as r,octetString as i,readSequenceChildren as a,sequence as o}from"../internal/asn1/der.js";import{decodeNonNegativeIntegerNumber as s,decodeObjectIdentifier as c,toArrayBuffer as l,toHex as u}from"../internal/asn1/asn1.js";import{OIDS as d}from"../internal/asn1/oids.js";import{getCrypto as f}from"../internal/crypto/webcrypto.js";import{failureResult as p,rethrowIfInvariant as m,successResult as h}from"../result/result.js";import{describeHashAlgorithm as g}from"../internal/crypto/algorithm-names.js";async function _(e,a){let s=a.iterations??2048;b(s);let c=a.salt??f().getRandomValues(new Uint8Array(16)),l=await x(e,a.password,c,s);return{der:o([o([o([r(d.sha256),n()]),i(l)]),i(c),t(s)]),parsed:{digestAlgorithmOid:d.sha256,digestAlgorithmName:g(d.sha256),digestHex:u(l),saltHex:u(c),iterations:s,verification:`valid`}}}async function v(e,t,n){let r=a(e),i=r[0],o=r[1],l=r[2];if(r.length!==3||i===void 0||o===void 0||l===void 0||o.tag!==4)throw Error(`Malformed MacData`);let f=e.slice(i.start-i.headerLength,i.end),p=a(f),m=p[0],h=p[1];if(p.length!==2||m===void 0||h===void 0||h.tag!==4)throw Error(`Malformed DigestInfo`);let _=a(f.slice(m.start-m.headerLength,m.end)),v=_[0];if(v===void 0||_.length!==1&&_.length!==2)throw Error(`MacData algorithm missing`);let y=c(v.value);if(y!==d.sha256)throw Error(`Only SHA-256 PKCS#12 MAC is supported`);let S=s(l.value,`MacData iterations`);if(b(S),n===void 0)return{digestAlgorithmOid:y,digestAlgorithmName:g(y),digestHex:u(h.value),saltHex:u(o.value),iterations:S,verification:`unchecked`};let C=await x(t,n,o.value,S);return{digestAlgorithmOid:y,digestAlgorithmName:g(y),digestHex:u(h.value),saltHex:u(o.value),iterations:S,verification:O(C,h.value)?`valid`:`invalid`}}async function y(e,t,n){try{return h(await v(e,t,n))}catch(e){return m(e),p(`malformed`,e instanceof Error?e.message:`Malformed MacData`)}}function b(e){if(!Number.isSafeInteger(e)||e<=0)throw Error(`MacData iterations must be a positive safe integer`)}async function x(e,t,n,r){let i=await S(t,n,r,3,32),a=await f().subtle.importKey(`raw`,l(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return new Uint8Array(await f().subtle.sign(`HMAC`,a,l(e)))}async function S(t,n,r,i,a){let o=new Uint8Array(64).fill(i),s=w(t),c=e([T(n,64),T(s,64)]),l=Math.ceil(a/32),u=new Uint8Array(l*32);for(let t=0;t<l;t+=1){let n=await C(e([o,c]));for(let e=1;e<r;e+=1)n=await C(n);if(u.set(n,t*32),c.length===0)continue;let i=E(n,64),a=new Uint8Array(c.length);for(let e=0;e<c.length/64;e+=1){let t=c.slice(e*64,e*64+64);D(t,i),a.set(t,e*64)}c=a}return u.slice(0,a)}async function C(e){return new Uint8Array(await f().subtle.digest(`SHA-256`,l(e)))}function w(e){let t=new Uint8Array((e.length+1)*2);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);t[n*2]=r>>8,t[n*2+1]=r&255}return t}function T(e,t){return e.length===0?new Uint8Array:E(e,t*Math.ceil(e.length/t))}function E(e,t){let n=new Uint8Array(t);for(let r=0;r<t;r+=1)n[r]=e[r%e.length]??0;return n}function D(e,t){let n=1;for(let r=e.length-1;r>=0;--r){let i=(e[r]??0)+(t[r]??0)+n;e[r]=i&255,n=i>>8}}function O(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=(e[r]??0)^(t[r]??0);return n===0}export{_ as createPkcs12MacData,y as parsePkcs12MacData,v as parsePkcs12MacDataOrThrow};
|
|
2
2
|
//# sourceMappingURL=pkcs12-mac.js.map
|
|
@@ -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.ts';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\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/** MAC verification outcome. Present only when a password was supplied during parsing. */\n\treadonly valid?: boolean;\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},\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and sets the `valid` flag on the returned structure.\n */\nexport async function parsePkcs12MacData(\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\tconst parsed: ParsedPkcs12MacData = {\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};\n\tif (password === undefined) {\n\t\treturn parsed;\n\t}\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsed.iterations,\n\t);\n\treturn { ...parsed, valid: equalBytes(expected, digest.value) };\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":"yeA0DA,eAAsB,EACrB,EACA,EAME,CACF,IAAM,EAAa,EAAQ,YAAc,KACzC,EAA0B,CAAU,EACpC,IAAM,EAAO,EAAQ,MAAQ,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACrE,EAAM,MAAM,EAAiB,EAAmB,EAAQ,SAAU,EAAM,CAAU,EAMxF,MAAO,CACN,IANW,EAAS,CACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,EAAG,EAAU,CAAC,CAAC,EAAG,EAAY,CAAG,CAAC,CAAC,EACnF,EAAY,CAAI,EAChB,EAAkB,CAAU,CAC7B,CAEG,EACF,OAAQ,CACP,mBAAoB,EAAK,OACzB,oBAAqB,EAAsB,EAAK,MAAM,EACtD,UAAW,EAAM,CAAG,EACpB,QAAS,EAAM,CAAI,EACnB,YACD,CACD,CACD,CAMA,eAAsB,EACrB,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,EAAqB,CAAG,EAC9B,EAAa,EAAI,GACjB,EAAO,EAAI,GACX,EAAa,EAAI,GACvB,GACC,EAAI,SAAW,GACf,IAAe,IAAA,IACf,IAAS,IAAA,IACT,IAAe,IAAA,IACf,EAAK,MAAQ,EAEb,MAAU,MAAM,mBAAmB,EAEpC,IAAM,EAAgB,EAAI,MAAM,EAAW,MAAQ,EAAW,aAAc,EAAW,GAAG,EACpF,EAAqB,EAAqB,CAAa,EACvD,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AI,EAAQ,EAAI,GAAK,EAAO,GAC7B,CACA,OAAO,CACR,CAGA,SAAS,EAAiB,EAAmB,EAA0B,CAItE,OAHI,EAAM,SAAW,EACb,IAAI,WAEL,EAAe,EAAO,EAAO,KAAK,KAAK,EAAM,OAAS,CAAI,CAAC,CACnE,CAGA,SAAS,EAAe,EAAmB,EAA4B,CACtE,IAAM,EAAM,IAAI,WAAW,CAAM,EACjC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,GAAS,EAC5C,EAAI,GAAS,EAAM,EAAQ,EAAM,SAAW,EAE7C,OAAO,CACR,CAGA,SAAS,EAAgB,EAAmB,EAA0B,CACrE,IAAI,EAAQ,EACZ,IAAK,IAAI,EAAQ,EAAM,OAAS,EAAG,GAAS,EAAG,IAAY,CAC1D,IAAM,GAAO,EAAM,IAAU,IAAM,EAAO,IAAU,GAAK,EACzD,EAAM,GAAS,EAAM,IACrB,EAAQ,GAAO,CAChB,CACD,CAGA,SAAS,EAAW,EAAkB,EAA4B,CACjE,GAAI,EAAK,SAAW,EAAM,OACzB,MAAO,GAER,IAAI,EAAS,EACb,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,OAAQ,GAAS,EACjD,IAAW,EAAK,IAAU,IAAM,EAAM,IAAU,GAEjD,OAAO,IAAW,CACnB"}
|
|
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\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\nimport {\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\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\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":"wkBAoEA,eAAsB,EACrB,EACA,EAME,CACF,IAAM,EAAa,EAAQ,YAAc,KACzC,EAA0B,CAAU,EACpC,IAAM,EAAO,EAAQ,MAAQ,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACrE,EAAM,MAAM,EAAiB,EAAmB,EAAQ,SAAU,EAAM,CAAU,EAMxF,MAAO,CACN,IANW,EAAS,CACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,EAAG,EAAU,CAAC,CAAC,EAAG,EAAY,CAAG,CAAC,CAAC,EACnF,EAAY,CAAI,EAChB,EAAkB,CAAU,CAC7B,CAEG,EACF,OAAQ,CACP,mBAAoB,EAAK,OACzB,oBAAqB,EAAsB,EAAK,MAAM,EACtD,UAAW,EAAM,CAAG,EACpB,QAAS,EAAM,CAAI,EACnB,aACA,aAAc,OACf,CACD,CACD,CAmBA,eAAsB,EACrB,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,EAAqB,CAAG,EAC9B,EAAa,EAAI,GACjB,EAAO,EAAI,GACX,EAAa,EAAI,GACvB,GACC,EAAI,SAAW,GACf,IAAe,IAAA,IACf,IAAS,IAAA,IACT,IAAe,IAAA,IACf,EAAK,MAAQ,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