micro509 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/index.d.ts +4 -4
  2. package/dist/index.js +15 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +626 -447
  47. package/dist/keys/keys.js +652 -404
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.d.ts +2 -2
  50. package/dist/keys.js +2 -2
  51. package/dist/pem/pem.d.ts +46 -46
  52. package/dist/pem/pem.js +62 -81
  53. package/dist/pem/pem.js.map +1 -0
  54. package/dist/pem.js +2 -2
  55. package/dist/pkcs/pfx.d.ts +96 -80
  56. package/dist/pkcs/pfx.js +191 -231
  57. package/dist/pkcs/pfx.js.map +1 -0
  58. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  59. package/dist/pkcs/pkcs12-mac.js +90 -111
  60. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  61. package/dist/pkcs/pkcs7.d.ts +118 -69
  62. package/dist/pkcs/pkcs7.js +401 -443
  63. package/dist/pkcs/pkcs7.js.map +1 -0
  64. package/dist/pkcs.d.ts +2 -2
  65. package/dist/pkcs.js +4 -4
  66. package/dist/result/result.d.ts +37 -32
  67. package/dist/result/result.js +46 -44
  68. package/dist/result/result.js.map +1 -0
  69. package/dist/result.js +2 -2
  70. package/dist/revocation/chain.d.ts +138 -119
  71. package/dist/revocation/chain.js +248 -281
  72. package/dist/revocation/chain.js.map +1 -0
  73. package/dist/revocation/crl.d.ts +125 -123
  74. package/dist/revocation/crl.js +653 -745
  75. package/dist/revocation/crl.js.map +1 -0
  76. package/dist/revocation/ocsp.d.ts +183 -177
  77. package/dist/revocation/ocsp.js +581 -638
  78. package/dist/revocation/ocsp.js.map +1 -0
  79. package/dist/revocation/revocation.d.ts +26 -26
  80. package/dist/revocation/revocation.js +104 -125
  81. package/dist/revocation/revocation.js.map +1 -0
  82. package/dist/revocation.js +5 -5
  83. package/dist/verify/identity.d.ts +42 -42
  84. package/dist/verify/identity.js +158 -167
  85. package/dist/verify/identity.js.map +1 -0
  86. package/dist/verify/name-constraints.d.ts +7 -7
  87. package/dist/verify/policy.d.ts +10 -10
  88. package/dist/verify/verify.d.ts +163 -163
  89. package/dist/verify/verify.js +396 -392
  90. package/dist/verify/verify.js.map +1 -0
  91. package/dist/verify.js +3 -3
  92. package/dist/x509/certificate.d.ts +117 -117
  93. package/dist/x509/certificate.js +51 -60
  94. package/dist/x509/certificate.js.map +1 -0
  95. package/dist/x509/csr.d.ts +25 -25
  96. package/dist/x509/csr.js +26 -30
  97. package/dist/x509/csr.js.map +1 -0
  98. package/dist/x509/extensions.d.ts +228 -184
  99. package/dist/x509/extensions.js +175 -200
  100. package/dist/x509/extensions.js.map +1 -0
  101. package/dist/x509/name.d.ts +94 -93
  102. package/dist/x509/name.js +30 -29
  103. package/dist/x509/name.js.map +1 -0
  104. package/dist/x509/parse.d.ts +185 -185
  105. package/dist/x509/parse.js +638 -676
  106. package/dist/x509/parse.js.map +1 -0
  107. package/dist/x509.js +6 -6
  108. package/package.json +79 -41
@@ -0,0 +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,EAAM,eAAe,CAAC,GAC9C,EAAe,KACd,oBAAoB,MAAM,oBAAoB,EAAW,UAAU,GAAG,EAAW,UAAU,CAC5F;CAED,IAAM,IAA6B,CAAC;CAIpC,IAHI,EAAgB,SAAS,KAC5B,EAAa,KAAK,sBAAsB,EAAS,CAAe,CAAC,C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M,IAAQ,oBAAoB,GAAQ,CAAO;CACjD,IAAI,EAAM,QAAQ,GACjB,MAAU,MAAM,wCAAwC;CAEzD,OAAO,EAAM;AACd;;AAGA,SAAS,oBAAoB,GAAoB,GAAiC;CACjF,KAAK,EAAQ,MAAM,QAAU,KAC5B,MAAU,MAAM,6CAA6C;CAE9D,IAAM,IAAW,EAAW,GAAQ,CAAO,GACrC,IAAQ,EAAS;CACvB,IAAI,EAAS,WAAW,KAAK,MAAU,KAAA,GACtC,MAAU,MAAM,0DAA0D;CAE3E,OAAO;AACR;;AAGA,SAAS,UAAU,GAA2B;CAC7C,IAAM,IAAQ,IAAI,WAAW,EAAM,SAAS,CAAC;CAC7C,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAM,QAAQ,KAAS,GAAG;EACrD,IAAM,IAAY,EAAM,WAAW,CAAK;EAExC,AADA,EAAM,IAAQ,KAAK,KAAa,GAChC,EAAM,IAAQ,IAAI,KAAK,IAAY;CACpC;CACA,OAAO,EAAI,IAAM,CAAK;AACvB;;AAGA,SAAS,gBAAgB,GAAyB;CACjD,IAAM,IAAU,EAAY,CAAG;CAC/B,IAAI,EAAQ,QAAQ,IACnB,MAAU,MAAM,oBAAoB;CAErC,IAAI,EAAQ,MAAM,SAAS,KAAM,GAChC,MAAU,MAAM,4CAA4C;CAE7D,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAQ,MAAM,QAAQ,KAAS,GAAG;EAC7D,IAAM,IAAO,EAAQ,MAAM,MAAU,GAC/B,IAAQ,EAAQ,MAAM,IAAQ,MAAM;EAC1C,KAAS,OAAO,aAAc,KAAQ,IAAK,CAAK;CACjD;CACA,OAAO;AACR"}
@@ -1,5 +1,4 @@
1
1
  import { ErrorResult, Micro509Error } from "../result/result.js";
2
-
3
2
  //#region src/pkcs/pkcs12-mac.d.ts
4
3
  /** Input for {@linkcode createPkcs12MacData}. */
5
4
  interface Pkcs12MacOptions {
@@ -23,17 +22,19 @@ interface ParsedPkcs12MacData {
23
22
  /** Number of PKCS#12 KDF iterations. */
24
23
  readonly iterations: number;
25
24
  /**
26
- * MAC verification outcome: `'unchecked'` when no password was supplied
27
- * during parsing, otherwise `'valid'` or `'invalid'`.
28
- */
25
+ * MAC verification outcome: `'unchecked'` when no password was supplied
26
+ * during parsing, otherwise `'valid'` or `'invalid'`.
27
+ */
29
28
  readonly verification: "valid" | "invalid" | "unchecked";
30
29
  }
31
30
  /**
32
- * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns
33
- * the DER-encoded MacData block alongside its parsed representation.
34
- */
31
+ * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns
32
+ * the DER-encoded MacData block alongside its parsed representation.
33
+ */
35
34
  declare function createPkcs12MacData(authenticatedSafe: Uint8Array, options: Pkcs12MacOptions): Promise<{
36
- /** DER-encoded MacData SEQUENCE. */readonly der: Uint8Array; /** Structured representation of the MAC parameters and digest. */
35
+ /** DER-encoded MacData SEQUENCE. */
36
+ readonly der: Uint8Array;
37
+ /** Structured representation of the MAC parameters and digest. */
37
38
  readonly parsed: ParsedPkcs12MacData;
38
39
  }>;
39
40
  /** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */
@@ -49,17 +50,18 @@ type ParsePkcs12MacDataResult = {
49
50
  readonly value: ParsedPkcs12MacData;
50
51
  } | ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;
51
52
  /**
52
- * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
53
- * provided, verifies the MAC and reports the outcome in `verification`.
54
- */
53
+ * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
54
+ * provided, verifies the MAC and reports the outcome in `verification`.
55
+ */
55
56
  declare function parsePkcs12MacDataOrThrow(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsedPkcs12MacData>;
56
57
  /**
57
- * Decodes a DER-encoded MacData block. When `password` is provided, verifies
58
- * the MAC and reports the outcome in `verification`.
59
- *
60
- * Returns a typed failure (`code: 'malformed'`) on malformed input. For the
61
- * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
62
- */
58
+ * Decodes a DER-encoded MacData block. When `password` is provided, verifies
59
+ * the MAC and reports the outcome in `verification`.
60
+ *
61
+ * Returns a typed failure (`code: 'malformed'`) on malformed input. For the
62
+ * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
63
+ */
63
64
  declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string): Promise<ParsePkcs12MacDataResult>;
64
65
  //#endregion
65
- export { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
66
+ export { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
67
+ //# sourceMappingURL=pkcs12-mac.d.ts.map
@@ -1,9 +1,9 @@
1
- import { concatBytes, integerFromNumber, nullValue, objectIdentifier, octetString, readSequenceChildren, sequence } from "../internal/asn1/der.js";
2
- import { decodeNonNegativeIntegerNumber, decodeObjectIdentifier, toArrayBuffer, toHex } from "../internal/asn1/asn1.js";
3
- import { OIDS } from "../internal/asn1/oids.js";
4
- import { getCrypto } from "../internal/crypto/webcrypto.js";
5
- import { failureResult, rethrowIfInvariant, successResult } from "../result/result.js";
6
- import { describeHashAlgorithm } from "../internal/crypto/algorithm-names.js";
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";
2
+ import { decodeNonNegativeIntegerNumber as s, decodeObjectIdentifier as c, toArrayBuffer as l, toHex as u } from "../internal/asn1/asn1.js";
3
+ import { OIDS as d } from "../internal/asn1/oids2.js";
4
+ import { getCrypto as f } from "../internal/crypto/webcrypto.js";
5
+ import { failureResult as p, rethrowIfInvariant as m, successResult as h } from "../result/result.js";
6
+ import { describeHashAlgorithm as g } from "../internal/crypto/algorithm-names.js";
7
7
  //#region src/pkcs/pkcs12-mac.ts
8
8
  /**
9
9
  * PKCS#12 MAC data creation and verification.
@@ -17,23 +17,22 @@ import { describeHashAlgorithm } from "../internal/crypto/algorithm-names.js";
17
17
  * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns
18
18
  * the DER-encoded MacData block alongside its parsed representation.
19
19
  */
20
- async function createPkcs12MacData(authenticatedSafe, options) {
21
- const iterations = options.iterations ?? 2048;
22
- assertPkcs12MacIterations(iterations);
23
- const salt = options.salt ?? getCrypto().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
24
- const mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);
20
+ async function createPkcs12MacData(e, a) {
21
+ let s = a.iterations ?? 2048;
22
+ assertPkcs12MacIterations(s);
23
+ let c = a.salt ?? f().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), l = await computePkcs12Mac(e, a.password, c, s);
25
24
  return {
26
- der: sequence([
27
- sequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),
28
- octetString(salt),
29
- integerFromNumber(iterations)
25
+ der: o([
26
+ o([o([r(d.sha256), n()]), i(l)]),
27
+ i(c),
28
+ t(s)
30
29
  ]),
31
30
  parsed: {
32
- digestAlgorithmOid: OIDS.sha256,
33
- digestAlgorithmName: describeHashAlgorithm(OIDS.sha256),
34
- digestHex: toHex(mac),
35
- saltHex: toHex(salt),
36
- iterations,
31
+ digestAlgorithmOid: d.sha256,
32
+ digestAlgorithmName: g(d.sha256),
33
+ digestHex: u(l),
34
+ saltHex: u(c),
35
+ iterations: s,
37
36
  verification: "valid"
38
37
  }
39
38
  };
@@ -42,40 +41,32 @@ async function createPkcs12MacData(authenticatedSafe, options) {
42
41
  * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
43
42
  * provided, verifies the MAC and reports the outcome in `verification`.
44
43
  */
45
- async function parsePkcs12MacDataOrThrow(der, authenticatedSafe, password) {
46
- const top = readSequenceChildren(der);
47
- const digestInfo = top[0];
48
- const salt = top[1];
49
- const iterations = top[2];
50
- if (top.length !== 3 || digestInfo === void 0 || salt === void 0 || iterations === void 0 || salt.tag !== 4) throw new Error("Malformed MacData");
51
- const digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);
52
- const digestInfoChildren = readSequenceChildren(digestInfoDer);
53
- const algorithm = digestInfoChildren[0];
54
- const digest = digestInfoChildren[1];
55
- if (digestInfoChildren.length !== 2 || algorithm === void 0 || digest === void 0 || digest.tag !== 4) throw new Error("Malformed DigestInfo");
56
- const algorithmChildren = readSequenceChildren(digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end));
57
- const algorithmOid = algorithmChildren[0];
58
- if (algorithmOid === void 0 || algorithmChildren.length !== 1 && algorithmChildren.length !== 2) throw new Error("MacData algorithm missing");
59
- const digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);
60
- if (digestAlgorithmOid !== OIDS.sha256) throw new Error("Only SHA-256 PKCS#12 MAC is supported");
61
- const parsedIterations = decodeNonNegativeIntegerNumber(iterations.value, "MacData iterations");
62
- assertPkcs12MacIterations(parsedIterations);
63
- if (password === void 0) return {
64
- digestAlgorithmOid,
65
- digestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),
66
- digestHex: toHex(digest.value),
67
- saltHex: toHex(salt.value),
68
- iterations: parsedIterations,
44
+ async function parsePkcs12MacDataOrThrow(e, t, n) {
45
+ let r = a(e), i = r[0], o = r[1], l = r[2];
46
+ if (r.length !== 3 || i === void 0 || o === void 0 || l === void 0 || o.tag !== 4) throw Error("Malformed MacData");
47
+ let f = e.slice(i.start - i.headerLength, i.end), p = a(f), m = p[0], h = p[1];
48
+ if (p.length !== 2 || m === void 0 || h === void 0 || h.tag !== 4) throw Error("Malformed DigestInfo");
49
+ let _ = a(f.slice(m.start - m.headerLength, m.end)), v = _[0];
50
+ if (v === void 0 || _.length !== 1 && _.length !== 2) throw Error("MacData algorithm missing");
51
+ let y = c(v.value);
52
+ if (y !== d.sha256) throw Error("Only SHA-256 PKCS#12 MAC is supported");
53
+ let b = s(l.value, "MacData iterations");
54
+ if (assertPkcs12MacIterations(b), n === void 0) return {
55
+ digestAlgorithmOid: y,
56
+ digestAlgorithmName: g(y),
57
+ digestHex: u(h.value),
58
+ saltHex: u(o.value),
59
+ iterations: b,
69
60
  verification: "unchecked"
70
61
  };
71
- const expected = await computePkcs12Mac(authenticatedSafe, password, salt.value, parsedIterations);
62
+ let x = await computePkcs12Mac(t, n, o.value, b);
72
63
  return {
73
- digestAlgorithmOid,
74
- digestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),
75
- digestHex: toHex(digest.value),
76
- saltHex: toHex(salt.value),
77
- iterations: parsedIterations,
78
- verification: equalBytes(expected, digest.value) ? "valid" : "invalid"
64
+ digestAlgorithmOid: y,
65
+ digestAlgorithmName: g(y),
66
+ digestHex: u(h.value),
67
+ saltHex: u(o.value),
68
+ iterations: b,
69
+ verification: equalBytes(x, h.value) ? "valid" : "invalid"
79
70
  };
80
71
  }
81
72
  /**
@@ -85,91 +76,79 @@ async function parsePkcs12MacDataOrThrow(der, authenticatedSafe, password) {
85
76
  * Returns a typed failure (`code: 'malformed'`) on malformed input. For the
86
77
  * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
87
78
  */
88
- async function parsePkcs12MacData(der, authenticatedSafe, password) {
79
+ async function parsePkcs12MacData(e, t, n) {
89
80
  try {
90
- return successResult(await parsePkcs12MacDataOrThrow(der, authenticatedSafe, password));
91
- } catch (error) {
92
- rethrowIfInvariant(error);
93
- return failureResult("malformed", error instanceof Error ? error.message : "Malformed MacData");
81
+ return h(await parsePkcs12MacDataOrThrow(e, t, n));
82
+ } catch (e) {
83
+ return m(e), p("malformed", e instanceof Error ? e.message : "Malformed MacData");
94
84
  }
95
85
  }
96
- function assertPkcs12MacIterations(iterations) {
97
- if (!Number.isSafeInteger(iterations) || iterations <= 0) throw new Error("MacData iterations must be a positive safe integer");
86
+ function assertPkcs12MacIterations(e) {
87
+ if (!Number.isSafeInteger(e) || e <= 0) throw Error("MacData iterations must be a positive safe integer");
98
88
  }
99
89
  /** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */
100
- async function computePkcs12Mac(authenticatedSafe, password, salt, iterations) {
101
- const keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);
102
- const key = await getCrypto().subtle.importKey("raw", toArrayBuffer(keyBytes), {
90
+ async function computePkcs12Mac(e, t, n, r) {
91
+ let i = await derivePkcs12Key(t, n, r, 3, 32), a = await f().subtle.importKey("raw", l(i), {
103
92
  name: "HMAC",
104
93
  hash: "SHA-256"
105
- }, false, ["sign"]);
106
- return new Uint8Array(await getCrypto().subtle.sign("HMAC", key, toArrayBuffer(authenticatedSafe)));
94
+ }, !1, ["sign"]);
95
+ return new Uint8Array(await f().subtle.sign("HMAC", a, l(e)));
107
96
  }
108
97
  /** PKCS#12 key derivation (RFC 7292 Appendix B). `id` selects the purpose (3 = MAC key). */
109
- async function derivePkcs12Key(password, salt, iterations, id, length) {
110
- const u = 32;
111
- const v = 64;
112
- const D = new Uint8Array(v).fill(id);
113
- const passwordBytes = encodePkcs12Password(password);
114
- let I = concatBytes([repeatToMultiple(salt, v), repeatToMultiple(passwordBytes, v)]);
115
- const blocks = Math.ceil(length / u);
116
- const output = new Uint8Array(blocks * u);
117
- for (let index = 0; index < blocks; index += 1) {
118
- let A = await digestSha256(concatBytes([D, I]));
119
- for (let round = 1; round < iterations; round += 1) A = await digestSha256(A);
120
- output.set(A, index * u);
121
- if (I.length === 0) continue;
122
- const B = repeatToLength(A, v);
123
- const next = new Uint8Array(I.length);
124
- for (let blockIndex = 0; blockIndex < I.length / v; blockIndex += 1) {
125
- const block = I.slice(blockIndex * v, blockIndex * v + v);
126
- addBlockInPlace(block, B);
127
- next.set(block, blockIndex * v);
98
+ async function derivePkcs12Key(t, n, r, i, a) {
99
+ let o = (/* @__PURE__ */ new Uint8Array(64)).fill(i), s = encodePkcs12Password(t), c = e([repeatToMultiple(n, 64), repeatToMultiple(s, 64)]), l = Math.ceil(a / 32), u = new Uint8Array(l * 32);
100
+ for (let t = 0; t < l; t += 1) {
101
+ let n = await digestSha256(e([o, c]));
102
+ for (let e = 1; e < r; e += 1) n = await digestSha256(n);
103
+ if (u.set(n, t * 32), c.length === 0) continue;
104
+ let i = repeatToLength(n, 64), a = new Uint8Array(c.length);
105
+ for (let e = 0; e < c.length / 64; e += 1) {
106
+ let t = c.slice(e * 64, e * 64 + 64);
107
+ addBlockInPlace(t, i), a.set(t, e * 64);
128
108
  }
129
- I = next;
109
+ c = a;
130
110
  }
131
- return output.slice(0, length);
111
+ return u.slice(0, a);
132
112
  }
133
113
  /** SHA-256 hash via WebCrypto. */
134
- async function digestSha256(bytes) {
135
- return new Uint8Array(await getCrypto().subtle.digest("SHA-256", toArrayBuffer(bytes)));
114
+ async function digestSha256(e) {
115
+ return new Uint8Array(await f().subtle.digest("SHA-256", l(e)));
136
116
  }
137
117
  /** Encodes a password as a null-terminated UCS-2 big-endian byte array (RFC 7292 B.1). */
138
- function encodePkcs12Password(password) {
139
- const out = new Uint8Array((password.length + 1) * 2);
140
- for (let index = 0; index < password.length; index += 1) {
141
- const code = password.charCodeAt(index);
142
- out[index * 2] = code >> 8;
143
- out[index * 2 + 1] = code & 255;
118
+ function encodePkcs12Password(e) {
119
+ let t = new Uint8Array((e.length + 1) * 2);
120
+ for (let n = 0; n < e.length; n += 1) {
121
+ let r = e.charCodeAt(n);
122
+ t[n * 2] = r >> 8, t[n * 2 + 1] = r & 255;
144
123
  }
145
- return out;
124
+ return t;
146
125
  }
147
126
  /** Repeats `bytes` to the nearest multiple of `size`. */
148
- function repeatToMultiple(bytes, size) {
149
- if (bytes.length === 0) return /* @__PURE__ */ new Uint8Array();
150
- return repeatToLength(bytes, size * Math.ceil(bytes.length / size));
127
+ function repeatToMultiple(e, t) {
128
+ return e.length === 0 ? /* @__PURE__ */ new Uint8Array() : repeatToLength(e, t * Math.ceil(e.length / t));
151
129
  }
152
130
  /** Cyclically repeats `bytes` to fill exactly `length` bytes. */
153
- function repeatToLength(bytes, length) {
154
- const out = new Uint8Array(length);
155
- for (let index = 0; index < length; index += 1) out[index] = bytes[index % bytes.length] ?? 0;
156
- return out;
131
+ function repeatToLength(e, t) {
132
+ let n = new Uint8Array(t);
133
+ for (let r = 0; r < t; r += 1) n[r] = e[r % e.length] ?? 0;
134
+ return n;
157
135
  }
158
136
  /** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */
159
- function addBlockInPlace(block, addend) {
160
- let carry = 1;
161
- for (let index = block.length - 1; index >= 0; index -= 1) {
162
- const sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;
163
- block[index] = sum & 255;
164
- carry = sum >> 8;
137
+ function addBlockInPlace(e, t) {
138
+ let n = 1;
139
+ for (let r = e.length - 1; r >= 0; --r) {
140
+ let i = (e[r] ?? 0) + (t[r] ?? 0) + n;
141
+ e[r] = i & 255, n = i >> 8;
165
142
  }
166
143
  }
167
144
  /** Constant-time byte comparison to avoid timing side-channels in MAC checks. */
168
- function equalBytes(left, right) {
169
- if (left.length !== right.length) return false;
170
- let result = 0;
171
- for (let index = 0; index < left.length; index += 1) result |= (left[index] ?? 0) ^ (right[index] ?? 0);
172
- return result === 0;
145
+ function equalBytes(e, t) {
146
+ if (e.length !== t.length) return !1;
147
+ let n = 0;
148
+ for (let r = 0; r < e.length; r += 1) n |= (e[r] ?? 0) ^ (t[r] ?? 0);
149
+ return n === 0;
173
150
  }
174
151
  //#endregion
175
152
  export { createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
153
+
154
+ //# sourceMappingURL=pkcs12-mac.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkcs12-mac.js","names":[],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based HMAC-SHA-256 integrity check\n * defined in PKCS#12 (RFC 7292), using the PKCS#12 key-derivation scheme.\n *\n * @module\n */\n\nimport {\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** Input for {@linkcode createPkcs12MacData}. */\nexport interface Pkcs12MacOptions {\n\t/** Password used to derive the HMAC key via the PKCS#12 KDF. */\n\treadonly password: string;\n\t/** PKCS#12 KDF iteration count. Default: `2048`. */\n\treadonly iterations?: number;\n\t/** Random salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n}\n\n/** Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. */\nexport interface ParsedPkcs12MacData {\n\t/** OID of the digest algorithm (currently always SHA-256). */\n\treadonly digestAlgorithmOid: string;\n\t/** Human-readable digest algorithm name (currently `\"SHA-256\"`). */\n\treadonly digestAlgorithmName: string;\n\t/** Hex-encoded MAC digest value. */\n\treadonly digestHex: string;\n\t/** Hex-encoded salt bytes used during key derivation. */\n\treadonly saltHex: string;\n\t/** Number of PKCS#12 KDF iterations. */\n\treadonly iterations: number;\n\t/**\n\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t */\n\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n}\n\n/**\n * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns\n * the DER-encoded MacData block alongside its parsed representation.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tconst iterations = options.iterations ?? 2048;\n\tassertPkcs12MacIterations(iterations);\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\tintegerFromNumber(iterations),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode = 'malformed';\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsedPkcs12MacData> {\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\ttop.length !== 3 ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrow new Error('Only SHA-256 PKCS#12 MAC is supported');\n\t}\n\tconst parsedIterations = decodeNonNegativeIntegerNumber(iterations.value, 'MacData iterations');\n\tassertPkcs12MacIterations(parsedIterations);\n\tif (password === undefined) {\n\t\treturn {\n\t\t\tdigestAlgorithmOid,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\t\tdigestHex: toHex(digest.value),\n\t\t\tsaltHex: toHex(salt.value),\n\t\t\titerations: parsedIterations,\n\t\t\tverification: 'unchecked',\n\t\t};\n\t}\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(await parsePkcs12MacDataOrThrow(der, authenticatedSafe, password));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed MacData');\n\t}\n}\n\nfunction assertPkcs12MacIterations(iterations: number): void {\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.sign('HMAC', key, toArrayBuffer(authenticatedSafe)),\n\t);\n}\n\n/** PKCS#12 key derivation (RFC 7292 Appendix B). `id` selects the purpose (3 = MAC key). */\nasync function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: number,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst S = repeatToMultiple(salt, v);\n\tconst P = repeatToMultiple(passwordBytes, v);\n\tlet I = concatBytes([S, P]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (I.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tconst next = new Uint8Array(I.length);\n\t\tfor (let blockIndex = 0; blockIndex < I.length / v; blockIndex += 1) {\n\t\t\tconst block = I.slice(blockIndex * v, blockIndex * v + v);\n\t\t\taddBlockInPlace(block, B);\n\t\t\tnext.set(block, blockIndex * v);\n\t\t}\n\t\tI = next;\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated UCS-2 big-endian byte array (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+DA,eAAsB,oBACrB,GACA,GAME;CACF,IAAM,IAAa,EAAQ,cAAc;CACzC,0BAA0B,CAAU;CACpC,IAAM,IAAO,EAAQ,QAAQ,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACrE,IAAM,MAAM,iBAAiB,GAAmB,EAAQ,UAAU,GAAM,CAAU;CAMxF,OAAO;EACN,KANW,EAAS;GACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,GAAG,EAAU,CAAC,CAAC,GAAG,EAAY,CAAG,CAAC,CAAC;GACnF,EAA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