micro509 0.14.0 → 0.16.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/CHANGELOG.md +2119 -0
- package/README.md +105 -225
- package/dist/crypto/crypto.d.ts +42 -11
- package/dist/crypto/crypto.js +53 -22
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +2 -2
- package/dist/crypto.js +1 -2
- package/dist/der/der.d.ts +41 -33
- package/dist/der/der.js +26 -24
- package/dist/der/der.js.map +1 -1
- package/dist/index.d.ts +11 -11
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +3 -6
- package/dist/internal/asn1/asn1.js +343 -43
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js +146 -0
- package/dist/internal/asn1/ber.js.map +1 -0
- package/dist/internal/asn1/decode-refusal.js +29 -0
- package/dist/internal/asn1/decode-refusal.js.map +1 -0
- package/dist/internal/asn1/der.d.ts +38 -41
- package/dist/internal/asn1/der.js +131 -52
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +83 -53
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids2.js +1 -2
- package/dist/internal/asn1/oids2.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js +1 -2
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js +13 -8
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js +1 -2
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +24 -11
- package/dist/internal/crypto/pbes2.js +79 -26
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js +46 -44
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +4 -7
- package/dist/internal/crypto/sig-verify.js +107 -60
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -4
- package/dist/internal/crypto/signing.js +28 -29
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/crypto/webcrypto.js +1 -2
- package/dist/internal/crypto/webcrypto.js.map +1 -1
- package/dist/internal/shared/base64.js +1 -2
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +3 -6
- package/dist/internal/shared/dn.js +99 -53
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna-tables.js +7217 -0
- package/dist/internal/shared/idna-tables.js.map +1 -0
- package/dist/internal/shared/idna.js +296 -0
- package/dist/internal/shared/idna.js.map +1 -0
- package/dist/internal/shared/ip.d.ts +4 -7
- package/dist/internal/shared/ip.js +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js +26 -0
- package/dist/internal/shared/mailbox.js.map +1 -0
- package/dist/internal/shared/punycode.js +101 -0
- package/dist/internal/shared/punycode.js.map +1 -0
- package/dist/internal/shared/rfc3454-tables.js +1 -2
- package/dist/internal/shared/rfc3454-tables.js.map +1 -1
- package/dist/internal/shared/rfc4518-tables.js +119 -0
- package/dist/internal/shared/rfc4518-tables.js.map +1 -0
- package/dist/internal/shared/uri-host.js +102 -0
- package/dist/internal/shared/uri-host.js.map +1 -0
- package/dist/internal/verify/name-constraints-engine.js +246 -131
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +6 -21
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js +23 -0
- package/dist/internal/verify/spki-distrust.js.map +1 -0
- package/dist/internal/verify/verify-path.d.ts +1 -4
- package/dist/internal/verify/verify-path.js +282 -129
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +1 -2
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js +2 -3
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -4
- package/dist/internal/x509/extension-errors.js +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +107 -89
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +129 -0
- package/dist/internal/x509/general-name-profile.js.map +1 -0
- package/dist/internal/x509/general-name-tags.js +1 -2
- package/dist/internal/x509/general-name-tags.js.map +1 -1
- package/dist/internal/x509/general-name.js +128 -42
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -2
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js +217 -0
- package/dist/internal/x509/or-address.js.map +1 -0
- package/dist/keys/keys.d.ts +122 -104
- package/dist/keys/keys.js +211 -204
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +3 -3
- package/dist/pem/pem.d.ts +14 -17
- package/dist/pem/pem.js +16 -17
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.js +1 -2
- package/dist/pkcs/pfx.d.ts +57 -32
- package/dist/pkcs/pfx.js +209 -173
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +104 -27
- package/dist/pkcs/pkcs12-mac.js +266 -79
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +43 -37
- package/dist/pkcs/pkcs7.js +218 -217
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +4 -3
- package/dist/result/result.d.ts +27 -20
- package/dist/result/result.js +8 -3
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +2 -2
- package/dist/result.js +1 -2
- package/dist/revocation/chain.d.ts +101 -23
- package/dist/revocation/chain.js +436 -182
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +131 -67
- package/dist/revocation/crl.js +443 -327
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +94 -59
- package/dist/revocation/ocsp.js +331 -293
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +47 -35
- package/dist/revocation/revocation.js +88 -57
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +3 -3
- package/dist/verify/identity.d.ts +16 -19
- package/dist/verify/identity.js +118 -89
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +1 -4
- package/dist/verify/policy.d.ts +9 -7
- package/dist/verify/verify.d.ts +115 -46
- package/dist/verify/verify.js +373 -183
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -2
- package/dist/x509/certificate.d.ts +20 -21
- package/dist/x509/certificate.js +62 -46
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +5 -7
- package/dist/x509/csr.js +10 -11
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +154 -66
- package/dist/x509/extensions.js +317 -151
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +15 -7
- package/dist/x509/fingerprint.js +20 -3
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +7 -9
- package/dist/x509/name-text.js +18 -4
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +9 -11
- package/dist/x509/name.js +18 -19
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +84 -69
- package/dist/x509/parse.js +421 -400
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +3 -3
- package/dist/x509.js +3 -3
- package/package.json +76 -59
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';\nimport type { DerElement } from '#micro509/internal/asn1/der';\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';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { decryptPbes2, encryptPbes2, isWrongPasswordError } from '#micro509/internal/crypto/pbes2';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { EncryptedPkcs8Options } from '#micro509/keys/keys';\nimport { exportPkcs8Der } from '#micro509/keys/keys';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type { ParsedPkcs12MacData, Pkcs12MacOptions } from '#micro509/pkcs/pkcs12-mac';\nimport { createPkcs12MacData, parsePkcs12MacData } from '#micro509/pkcs/pkcs12-mac';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult } from '#micro509/result/result';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\n\nexport type * from '#micro509/pkcs/pkcs12-mac';\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 EncryptedPkcs8Options}. */\nexport type PfxEncryptionOptions = EncryptedPkcs8Options;\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// Result types for PFX parsing\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// Result types for PFX creation\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// createPfx\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// parsePfxDer / parsePfxPem — Result-returning\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 function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\tlet bytes: Uint8Array;\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 Promise.resolve(pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block'));\n\t\t}\n\t\tbytes = block.bytes;\n\t} catch {\n\t\treturn Promise.resolve(pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block'));\n\t}\n\treturn parsePfxDer(bytes, options);\n}\n\n// Private: PFX helpers\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\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t} catch (error) {\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t};\n\t}\n\ttry {\n\t\treadSequenceChildren(decrypted);\n\t} catch {\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n\treturn { data: decrypted };\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\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nfunction normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\treturn source instanceof CryptoKey\n\t\t? exportPkcs8Der(source)\n\t\t: Promise.resolve(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. */\nfunction decryptEncryptedData(encryptedDataDer: Uint8Array, password: string): 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyPA,eAAsB,UAAU,GAAiD;CAChF,IAAM,IAAgC,CAAC,GACjC,IAA+B,CAAC;CACtC,KAAK,IAAM,KAAe,EAAM,gBAAgB,CAAC,GAAG;EAGnD,IAAI;EACJ,IAAI;GACH,IAAiB,qBAAqB,EAAY,WAAW;EAC9D,QAAQ;GACP,OAAO,mBACN,uBACA,qEACD;EACD;EACA,EAAgB,KAAK,qBAAqB,GAAgB,EAAY,UAAU,CAAC;CAClF;CACA,KAAK,IAAM,KAAc,EA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,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"pfx.js","names":["certificateBags","privateKeyBags","certificate","input","certificateDer","privateKey","contentInfos","sequence","safeContents","authenticatedSafe","macData","createPkcs12MacData","der","integerFromNumber","pemEncode","base64Encode","failureResult","code","message","options","createKdfBudget","topLevel","berSequenceChildren","readBerRoot","version","authSafe","decodeIntegerNumber","berPrimitiveContent","authenticatedSafeOctets","macElement","macResult","berToDefiniteLength","bags","contentInfo","safeContentsResult","budget","bag","error","refusal","decodeRefusalOf","DECODE_REFUSAL_CODES","bytes","blocks","splitPemBlocksOrThrow","pem","block","source","oid","OIDS","content","children","contentType","decodeObjectIdentifier","DECODE_LIMIT_CODES","data","encryptedData","decrypted","rethrowIfInvariant","isWrongPasswordError","isKdfIterationLimitError","root","certBag","objectIdentifier","explicitContext","octetString","attributes","pkcs8Der","encryption","encryptPbes2","tlv","out","setOf","throwMicro509Error","friendlyName","bmpString","bagId","bagValue","attributeSet","bagOid","value","certBagChildren","certType","certValue","parseCertificateDerOrThrow","berEncoding","readRootElement","entries","localKeyId","attribute","parts","values","attrOid","rawValues","toHex","firstValue","element","readElement","exportPkcs8Der","candidate","parsePkcs12MacData","macDataDer","encryptedContentInfo","contentInfoChildren","algorithm","encryptedContent","decryptPbes2","berStringContent","password","child","decodeString"],"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\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport type { BerElement } from '#micro509/internal/asn1/ber';\nimport {\n\tberEncoding,\n\tberPrimitiveContent,\n\tberSequenceChildren,\n\tberStringContent,\n\tberToDefiniteLength,\n\treadBerRoot,\n} from '#micro509/internal/asn1/ber';\nimport {\n\tDECODE_LIMIT_CODES,\n\tDECODE_REFUSAL_CODES,\n\tdecodeRefusalOf,\n} from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tbmpString,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { KdfBudget, KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\nimport {\n\tcreateKdfBudget,\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisKdfIterationLimitError,\n\tisWrongPasswordError,\n} from '#micro509/internal/crypto/pbes2';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { EncryptedPkcs8Options } from '#micro509/keys/keys';\nimport { exportPkcs8Der } from '#micro509/keys/keys';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type { ParsedPkcs12MacData, Pkcs12MacOptions } from '#micro509/pkcs/pkcs12-mac';\nimport { createPkcs12MacData, parsePkcs12MacData } from '#micro509/pkcs/pkcs12-mac';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, throwMicro509Error } from '#micro509/result/result';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\n\nexport type * from '#micro509/pkcs/pkcs12-mac';\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/**\n\t * Human-readable label stored as a BMPString attribute of 1 to 255 characters\n\t * (RFC 2985 §5.5.1), none of them a surrogate, U+FFFE or U+FFFF.\n\t */\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: the RFC 7292 MAC or RFC 9879 PBMAC1. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode EncryptedPkcs8Options}. */\nexport type PfxEncryptionOptions = EncryptedPkcs8Options;\n\nexport type { KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions extends KdfLimitOptions {\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/**\n\t * Hex of each received attribute value, re-encoded with definite lengths.\n\t * Universal constructed strings are joined into primitive strings. SET OF\n\t * order and implicitly tagged constructed strings stay as received.\n\t */\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/**\n\t\t\t * The received bag value, re-encoded with definite lengths. Universal\n\t\t\t * constructed strings are joined into primitive strings. SET OF order and\n\t\t\t * implicitly tagged constructed strings stay as received.\n\t\t\t */\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// Result types for PFX parsing\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode =\n\t| DecodeFailureCode\n\t| 'invalid_password'\n\t| 'password_required'\n\t| 'kdf_iterations_exceeded'\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'unsupported_mac_algorithm'\n\t| 'weak_mac_key_length';\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// Result types for PFX creation\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/** Bag attribute input that {@linkcode createPfx} refuses by throwing a `ResultError`. */\nexport type PfxEncoderErrorCode = 'invalid_friendly_name';\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// createPfx\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 * When `mac` is provided, `mac.type` selects the RFC 7292 MAC (the default) or\n * RFC 9879 PBMAC1.\n *\n * @throws {ResultError} with a {@linkcode CreatePkcs12MacDataErrorCode} when `mac.iterations`\n * is out of range or `mac.password` cannot be encoded for the selected MAC, and with\n * {@linkcode PfxEncoderErrorCode} `invalid_friendly_name` when a bag `friendlyName` is not a\n * BMPString of 1 to 255 characters.\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// parsePfxDer / parsePfxPem — Result-returning\n\n/**\n * Decodes a BER- or DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * The PFX, AuthenticatedSafe and SafeContents layers accept BER: indefinite and\n * non-minimal lengths and constructed OCTET STRINGs. The MAC is verified over the\n * AuthenticatedSafe octets as received. Certificates and private keys inside the\n * bags must be DER.\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\treturn await parsePfxDerWithBudget(der, options, createKdfBudget(options));\n}\n\nasync function parsePfxDerWithBudget(\n\tder: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = berSequenceChildren(readBerRoot(der));\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) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(berPrimitiveContent(der, version, 0x02)) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authenticatedSafeOctets = extractContentInfoData(der, authSafe);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await verifyPfxMacData(\n\t\t\t\tberToDefiniteLength(der, macElement),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions,\n\t\t\t);\n\t\t\tif (macResult.error !== undefined) {\n\t\t\t\treturn macResult.error;\n\t\t\t}\n\t\t\tmacData = macResult.macData;\n\t\t}\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of berSequenceChildren(readBerRoot(authenticatedSafeOctets))) {\n\t\t\tconst safeContentsResult = await extractSafeContents(\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\tcontentInfo,\n\t\t\t\toptions,\n\t\t\t\tbudget,\n\t\t\t);\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 berSequenceChildren(safeContentsResult.root)) {\n\t\t\t\tbags.push(parseSafeBag(safeContents, bag));\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 (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? pfxFailure('malformed', 'Malformed PFX structure')\n\t\t\t: pfxFailure(refusal.code, refusal.message);\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\tconst budget = createKdfBudget(options);\n\tlet bytes: Uint8Array;\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\tbytes = block.bytes;\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n\treturn await parsePfxDerWithBudget(bytes, options, budget);\n}\n\n// Private: PFX helpers\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(source: Uint8Array, contentInfo: BerElement): Uint8Array {\n\tconst { oid, content } = readContentInfo(source, contentInfo);\n\tif (oid !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(source, content);\n}\n\nfunction readContentInfo(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n): { readonly oid: string; readonly content: BerElement } {\n\tconst children = berSequenceChildren(contentInfo);\n\tconst contentType = children[0];\n\tconst content = children[1];\n\tif (contentType === undefined || content === undefined || children.length !== 2) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\treturn {\n\t\toid: decodeObjectIdentifier(berPrimitiveContent(source, contentType, 0x06)),\n\t\tcontent,\n\t};\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly root: BerElement;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly root?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tlet oid: string;\n\tlet content: BerElement;\n\ttry {\n\t\t({ oid, content } = readContentInfo(source, contentInfo));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed ContentInfo')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\tif (oid === OIDS.pkcs7Data) {\n\t\tconst data = extractContextOctetString(source, content);\n\t\treturn { data, root: readBerRoot(data) };\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(content);\n\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(source, encryptedData, options.password, budget);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn { error: pfxFailure('kdf_iterations_exceeded', error.message) };\n\t\t}\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX encrypted content')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\ttry {\n\t\tconst root = readBerRoot(decrypted);\n\t\tberSequenceChildren(root);\n\t\treturn { data: decrypted, root };\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal !== undefined) {\n\t\t\treturn { error: pfxFailure(refusal.code, refusal.message) };\n\t\t}\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\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([\n\t\t\t\tobjectIdentifier(OIDS.friendlyName),\n\t\t\t\tsetOf([encodeFriendlyName(attributes.friendlyName)]),\n\t\t\t]),\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/** RFC 2985 §5.5.1: `pkcs-9-ub-friendlyName`. */\nconst MAX_FRIENDLY_NAME_LENGTH = 255;\n\nfunction encodeFriendlyName(friendlyName: string): Uint8Array {\n\tconst refuse = (): never =>\n\t\tthrowMicro509Error<PfxEncoderErrorCode>(\n\t\t\t'invalid_friendly_name',\n\t\t\t'friendlyName must be a BMPString of 1 to 255 characters, none of them a surrogate, U+FFFE or U+FFFF',\n\t\t);\n\tif (friendlyName.length === 0 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\treturn refuse();\n\t}\n\ttry {\n\t\treturn bmpString(friendlyName);\n\t} catch {\n\t\treturn refuse();\n\t}\n}\n\n/** Decodes a single SafeBag into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(source: Uint8Array, bag: BerElement): ParsedPfxBag {\n\tconst children = berSequenceChildren(bag);\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(berPrimitiveContent(source, bagId, 0x06));\n\tconst attributes = parseBagAttributes(source, attributeSet);\n\tconst value = extractContextChild(bagValue);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBagChildren = berSequenceChildren(value);\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(berPrimitiveContent(source, certType, 0x06)) !==\n\t\t\t\tOIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(extractContextOctetString(source, certValue)),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8Der = berEncoding(source, value);\n\t\treadRootElement(pkcs8Der);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der,\n\t\t};\n\t}\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: berToDefiniteLength(source, value),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: BerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tif (attributeSet.tag !== 0x31) {\n\t\tthrow new Error('Malformed PFX bag attributes');\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of attributeSet.children) {\n\t\tconst parts = berSequenceChildren(attribute);\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(berPrimitiveContent(source, oid, 0x06));\n\t\tconst rawValues = values.children.map((value) => berToDefiniteLength(source, value));\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 = decodeFriendlyName(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\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nfunction normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\treturn source instanceof CryptoKey\n\t\t? exportPkcs8Der(source)\n\t\t: Promise.resolve(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/** Parses the MacData block and verifies it against the AuthenticatedSafe when a password is given. */\nasync function verifyPfxMacData(\n\tmacDataDer: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| { readonly macData: ParsedPkcs12MacData; readonly error?: undefined }\n\t| {\n\t\t\treadonly macData?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst macResult = await parsePkcs12MacData(\n\t\tmacDataDer,\n\t\tauthenticatedSafe,\n\t\toptions?.macPassword ?? options?.password,\n\t\toptions,\n\t);\n\tif (!macResult.ok) {\n\t\treturn {\n\t\t\terror:\n\t\t\t\tmacResult.code === 'malformed'\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX MacData')\n\t\t\t\t\t: pfxFailure(macResult.code, macResult.message),\n\t\t};\n\t}\n\tif (macResult.value.verification === 'invalid') {\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content'),\n\t\t};\n\t}\n\treturn { macData: macResult.value };\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nfunction decryptEncryptedData(\n\tsource: Uint8Array,\n\tencryptedData: BerElement,\n\tpassword: string,\n\tbudget: KdfBudget,\n): Promise<Uint8Array> {\n\tconst topLevel = berSequenceChildren(encryptedData);\n\tconst version = topLevel[0];\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || version === undefined || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tif (decodeIntegerNumber(berPrimitiveContent(source, version, 0x02)) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoChildren = berSequenceChildren(encryptedContentInfo);\n\tconst contentType = contentInfoChildren[0];\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\tcontentType === undefined ||\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tberPrimitiveContent(source, contentType, 0x06);\n\treturn decryptPbes2(\n\t\tberToDefiniteLength(source, algorithm),\n\t\tberStringContent(source, encryptedContent, 0x80, 0x04),\n\t\tpassword,\n\t\tbudget,\n\t);\n}\n\n/** Reads the OCTET STRING inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextOctetString(source: Uint8Array, element: BerElement): Uint8Array {\n\treturn berStringContent(source, extractContextChild(element), 0x04);\n}\n\n/** Reads the single child element inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextChild(element: BerElement): BerElement {\n\tif (element.tag !== 0xa0) {\n\t\tthrow new Error('Expected [0] EXPLICIT value');\n\t}\n\tconst child = element.children[0];\n\tif (element.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/** RFC 2985 §5.5.1: a friendlyName value is a BMPString of SIZE (1..255). */\nfunction decodeFriendlyName(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('friendlyName must be a BMPString');\n\t}\n\tconst friendlyName = decodeString(0x1e, element.value);\n\tif (friendlyName.length < 1 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\tthrow new Error('friendlyName must hold 1 to 255 characters');\n\t}\n\treturn friendlyName;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6SA,eAAsB,UAAU,GAAiD;CAChF,IAAMA,IAAgC,CAAC,GACjCC,IAA+B,CAAC;CACtC,KAAK,IAAMC,KAAeC,EAAM,gBAAgB,CAAC,GAAG;EAGnD,IAAIC;EACJ,IAAI;GACH,IAAiB,qBAAqBF,EAAY,WAAW;EAC9D,QAAQ;GACP,OAAO,mBACN,uBACA,qEACD;EACD;EACA,EAAgB,KAAK,qBAAqBE,GAAgBF,EAAY,UAAU,CAAC;CAClF;CACA,KAAK,IAAMG,KAAcF,EAAM,eAAe,CAAC,GAC9C,EAAe,KACd,oBAAoB,MAAM,oBAAoBE,EAAW,UAAU,GAAGA,EAAW,UAAU,CAC5F;CAED,IAAMC,IAA6B,CAAC;CAIpC,IAHIN,EAAgB,SAAS,KAC5BM,EAAa,KAAK,sBAAsBC,EAASP,CAAe,CAAC,CAAC,GAE/DC,EAAe,SAAS,GAAG;EAC9B,IAAMO,IAAeD,EAASN,CAAc;EAC5C,EAAa,KACZE,EAAM,eAAe,KAAA,IAClB,sBAAsBK,CAAY,IAClC,MAAM,+BAA+BA,GAAcL,EAAM,UAAU,CACvE;CACD;CACA,IAAMM,IAAoBF,EAASD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B,GAAiC;CAC7D,IAAIA,EAAQ,QAAQ,KACnB,MAAU,MAAM,6BAA6B;CAE9C,IAAMa,IAAQb,EAAQ,SAAS;CAC/B,IAAIA,EAAQ,SAAS,WAAW,KAAKa,MAAU,KAAA,GAC9C,MAAU,MAAM,0DAA0D;CAE3E,OAAOA;AACR;;AAGA,SAAS,mBAAmB,GAAyB;CACpD,IAAMb,IAAUC,EAAYpF,CAAG;CAC/B,IAAImF,EAAQ,QAAQ,IACnB,MAAU,MAAM,kCAAkC;CAEnD,IAAMtB,IAAeoC,EAAa,IAAMd,EAAQ,KAAK;CACrD,IAAItB,EAAa,SAAS,KAAKA,EAAa,SAAS,KACpD,MAAU,MAAM,4CAA4C;CAE7D,OAAOA;AACR"}
|
|
@@ -1,67 +1,144 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { KdfLimitOptions } from "../internal/crypto/pbes2.js";
|
|
2
|
+
import { DecodeFailureCode, ErrorResult, Micro509Error } from "../result/result.js";
|
|
3
|
+
/** Machine-readable reason {@linkcode createPkcs12MacData} rejected its construction input. */
|
|
4
|
+
export type CreatePkcs12MacDataErrorCode = "password_not_bmp_string" | "password_not_utf8" | "invalid_iterations";
|
|
5
|
+
/**
|
|
6
|
+
* Input for {@linkcode createPkcs12MacData}. `type` selects the MAC: `'pkcs12-kdf'` (the
|
|
7
|
+
* default) is the RFC 7292 HMAC-SHA-256 MAC keyed by the PKCS#12 KDF, and `'pbmac1'` is
|
|
8
|
+
* RFC 9879 PBMAC1 with PBKDF2-HMAC-SHA-256, a 32-octet key and HMAC-SHA-256.
|
|
9
|
+
*/
|
|
10
|
+
export type Pkcs12MacOptions = {
|
|
11
|
+
/** RFC 7292 Appendix B key derivation with HMAC-SHA-256. */
|
|
12
|
+
readonly type?: "pkcs12-kdf";
|
|
13
|
+
/**
|
|
14
|
+
* Password used to derive the HMAC key via the PKCS#12 KDF. Every character must be a
|
|
15
|
+
* BMPString character, so UTF-16 surrogates, U+FFFE and U+FFFF are rejected.
|
|
16
|
+
*/
|
|
6
17
|
readonly password: string;
|
|
7
|
-
/** PKCS#12 KDF iteration count. Default: `2048`. */
|
|
18
|
+
/** PKCS#12 KDF iteration count, a positive safe integer. Default: `2048`. */
|
|
8
19
|
readonly iterations?: number;
|
|
9
20
|
/** Random salt. Default: 16 cryptographically random bytes. */
|
|
10
21
|
readonly salt?: Uint8Array;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
/**
|
|
22
|
+
} | {
|
|
23
|
+
/** RFC 9879 PBMAC1. */
|
|
24
|
+
readonly type: "pbmac1";
|
|
25
|
+
/**
|
|
26
|
+
* Password fed to PBKDF2 as UTF-8 without a NULL terminator. Unpaired UTF-16
|
|
27
|
+
* surrogates are rejected.
|
|
28
|
+
*/
|
|
29
|
+
readonly password: string;
|
|
30
|
+
/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */
|
|
31
|
+
readonly iterations?: number;
|
|
32
|
+
/** PBKDF2 salt, also written to the ignored MacData macSalt. Default: 16 random bytes. */
|
|
33
|
+
readonly salt?: Uint8Array;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. `type` names the
|
|
37
|
+
* MAC: `'pkcs12-kdf'` for the RFC 7292 MAC and `'pbmac1'` for RFC 9879 PBMAC1.
|
|
38
|
+
*/
|
|
39
|
+
export type ParsedPkcs12MacData = {
|
|
40
|
+
/** RFC 7292 MAC keyed by the PKCS#12 KDF. */
|
|
41
|
+
readonly type: "pkcs12-kdf";
|
|
42
|
+
/** OID of the digest algorithm (always SHA-256). */
|
|
15
43
|
readonly digestAlgorithmOid: string;
|
|
16
|
-
/** Human-readable digest algorithm name (
|
|
44
|
+
/** Human-readable digest algorithm name (`"SHA-256"`). */
|
|
17
45
|
readonly digestAlgorithmName: string;
|
|
18
46
|
/** Hex-encoded MAC digest value. */
|
|
19
47
|
readonly digestHex: string;
|
|
20
|
-
/** Hex-encoded
|
|
48
|
+
/** Hex-encoded MacData macSalt. */
|
|
21
49
|
readonly saltHex: string;
|
|
22
|
-
/**
|
|
50
|
+
/** MacData iterations, the PKCS#12 KDF iteration count. */
|
|
23
51
|
readonly iterations: number;
|
|
24
52
|
/**
|
|
25
53
|
* MAC verification outcome: `'unchecked'` when no password was supplied
|
|
26
54
|
* during parsing, otherwise `'valid'` or `'invalid'`.
|
|
27
55
|
*/
|
|
28
56
|
readonly verification: "valid" | "invalid" | "unchecked";
|
|
29
|
-
}
|
|
57
|
+
} | {
|
|
58
|
+
/** RFC 9879 PBMAC1 keyed by PBKDF2. */
|
|
59
|
+
readonly type: "pbmac1";
|
|
60
|
+
/** The id-PBMAC1 OID. */
|
|
61
|
+
readonly digestAlgorithmOid: string;
|
|
62
|
+
/** Always `"PBMAC1"`. */
|
|
63
|
+
readonly digestAlgorithmName: string;
|
|
64
|
+
/** Hex-encoded MAC value. */
|
|
65
|
+
readonly digestHex: string;
|
|
66
|
+
/** Hex-encoded PBKDF2 salt. MacData macSalt is ignored. */
|
|
67
|
+
readonly saltHex: string;
|
|
68
|
+
/** PBKDF2 iteration count. MacData iterations is ignored. */
|
|
69
|
+
readonly iterations: number;
|
|
70
|
+
/** PBKDF2 keyLength in octets. */
|
|
71
|
+
readonly keyLength: number;
|
|
72
|
+
/** PBKDF2 pseudorandom function. */
|
|
73
|
+
readonly prf: "HMAC-SHA-256" | "HMAC-SHA-384" | "HMAC-SHA-512";
|
|
74
|
+
/** PBMAC1 message authentication scheme. */
|
|
75
|
+
readonly messageAuthScheme: "HMAC-SHA-256" | "HMAC-SHA-384" | "HMAC-SHA-512";
|
|
76
|
+
/**
|
|
77
|
+
* MAC verification outcome: `'unchecked'` when no password was supplied
|
|
78
|
+
* during parsing, otherwise `'valid'` or `'invalid'`.
|
|
79
|
+
*/
|
|
80
|
+
readonly verification: "valid" | "invalid" | "unchecked";
|
|
81
|
+
};
|
|
30
82
|
/**
|
|
31
|
-
* Computes a PKCS#12
|
|
32
|
-
*
|
|
83
|
+
* Computes a PKCS#12 MAC over the AuthenticatedSafe and returns the DER-encoded MacData
|
|
84
|
+
* block alongside its parsed representation.
|
|
85
|
+
*
|
|
86
|
+
* @throws {ResultError} with code `invalid_iterations` when `iterations` is out of range,
|
|
87
|
+
* `password_not_bmp_string` when a `'pkcs12-kdf'` password contains a UTF-16 surrogate, U+FFFE
|
|
88
|
+
* or U+FFFF, and `password_not_utf8` when a `'pbmac1'` password contains an unpaired UTF-16
|
|
89
|
+
* surrogate.
|
|
33
90
|
*/
|
|
34
|
-
declare function createPkcs12MacData(authenticatedSafe: Uint8Array, options: Pkcs12MacOptions): Promise<{
|
|
91
|
+
export declare function createPkcs12MacData(authenticatedSafe: Uint8Array, options: Pkcs12MacOptions): Promise<{
|
|
35
92
|
/** DER-encoded MacData SEQUENCE. */
|
|
36
93
|
readonly der: Uint8Array;
|
|
37
94
|
/** Structured representation of the MAC parameters and digest. */
|
|
38
95
|
readonly parsed: ParsedPkcs12MacData;
|
|
39
96
|
}>;
|
|
40
97
|
/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */
|
|
41
|
-
type ParsePkcs12MacDataErrorCode = "
|
|
98
|
+
export type ParsePkcs12MacDataErrorCode = Exclude<DecodeFailureCode, "unsupported"> | "kdf_iterations_exceeded" | "password_not_bmp_string" | "password_not_utf8" | "unsupported_mac_algorithm" | "weak_mac_key_length";
|
|
99
|
+
/** Options for {@linkcode parsePkcs12MacData} and {@linkcode parsePkcs12MacDataOrThrow}. */
|
|
100
|
+
export type ParsePkcs12MacDataOptions = KdfLimitOptions;
|
|
42
101
|
/** Structured failure payload for MacData parsing. */
|
|
43
|
-
interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {
|
|
102
|
+
export interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {
|
|
44
103
|
/** Always `false` for failures. */
|
|
45
104
|
readonly ok: false;
|
|
46
105
|
}
|
|
47
106
|
/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */
|
|
48
|
-
type ParsePkcs12MacDataResult = {
|
|
107
|
+
export type ParsePkcs12MacDataResult = {
|
|
49
108
|
readonly ok: true;
|
|
50
109
|
readonly value: ParsedPkcs12MacData;
|
|
51
110
|
} | ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;
|
|
52
111
|
/**
|
|
53
112
|
* Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
|
|
54
|
-
* provided, verifies the MAC and reports the outcome in `verification
|
|
113
|
+
* provided, verifies the MAC and reports the outcome in `verification`, and
|
|
114
|
+
* throws before deriving when the iteration count exceeds
|
|
115
|
+
* `options.maxKdfIterations` or {@linkcode Number.MAX_SAFE_INTEGER}. The
|
|
116
|
+
* default limit is `100_000` for the PKCS#12 KDF and `2_000_000` for the
|
|
117
|
+
* PBKDF2 behind PBMAC1. Without `password` no key is derived, so
|
|
118
|
+
* `options.maxKdfIterations` is not applied and `verification` is
|
|
119
|
+
* `'unchecked'`. Throws a {@linkcode ResultError} carrying a
|
|
120
|
+
* {@linkcode ParsePkcs12MacDataErrorCode} for an unsupported MAC, a PBMAC1 key
|
|
121
|
+
* length below 20 octets, or a password the MAC cannot encode.
|
|
55
122
|
*/
|
|
56
|
-
declare function parsePkcs12MacDataOrThrow(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsedPkcs12MacData>;
|
|
123
|
+
export declare function parsePkcs12MacDataOrThrow(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string, options?: ParsePkcs12MacDataOptions): Promise<ParsedPkcs12MacData>;
|
|
57
124
|
/**
|
|
58
125
|
* Decodes a DER-encoded MacData block. When `password` is provided, verifies
|
|
59
126
|
* the MAC and reports the outcome in `verification`.
|
|
60
127
|
*
|
|
61
|
-
* Returns a typed failure (`code: 'malformed'`) on malformed input
|
|
62
|
-
*
|
|
128
|
+
* Returns a typed failure (`code: 'malformed'`) on malformed input, an
|
|
129
|
+
* iteration count below 1, or a PBMAC1 iteration count above 4294967295,
|
|
130
|
+
* `'unsupported_mac_algorithm'` for a MAC other than
|
|
131
|
+
* the RFC 7292 SHA-256 MAC or a PBMAC1 variant this implementation does not
|
|
132
|
+
* handle, `'weak_mac_key_length'` for a PBMAC1 key length below 20 octets,
|
|
133
|
+
* `'password_not_bmp_string'` when an RFC 7292 password contains a UTF-16
|
|
134
|
+
* surrogate, U+FFFE or U+FFFF, and `'password_not_utf8'` when a PBMAC1 password contains an
|
|
135
|
+
* unpaired UTF-16 surrogate. With a `password`, returns
|
|
136
|
+
* `code: 'kdf_iterations_exceeded'` when the iteration count exceeds
|
|
137
|
+
* `options.maxKdfIterations`, or an RFC 7292 MAC count exceeds
|
|
138
|
+
* {@linkcode Number.MAX_SAFE_INTEGER}. Without a `password` no key is derived:
|
|
139
|
+
* `options.maxKdfIterations` is not applied, an RFC 7292 MAC count above
|
|
140
|
+
* {@linkcode Number.MAX_SAFE_INTEGER} is `'malformed'`, and `verification` is
|
|
141
|
+
* `'unchecked'`. For the throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
|
|
63
142
|
*/
|
|
64
|
-
declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsePkcs12MacDataResult>;
|
|
65
|
-
//#endregion
|
|
66
|
-
export { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
|
|
143
|
+
export declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string, options?: ParsePkcs12MacDataOptions): Promise<ParsePkcs12MacDataResult>;
|
|
67
144
|
//# sourceMappingURL=pkcs12-mac.d.ts.map
|