micro509 0.17.1 → 0.19.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 (183) hide show
  1. package/CHANGELOG.md +165 -6
  2. package/dist/crypto/crypto.d.ts +12 -4
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +8 -2
  6. package/dist/der/der.d.ts +14 -4
  7. package/dist/der/der.js +19 -19
  8. package/dist/der/der.js.map +1 -1
  9. package/dist/der.d.ts +26 -2
  10. package/dist/der.js +4 -4
  11. package/dist/index.d.ts +84 -16
  12. package/dist/index.js +19 -19
  13. package/dist/internal/asn1/asn1.d.ts +1 -2
  14. package/dist/internal/asn1/asn1.js +10 -2
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js.map +1 -1
  17. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  18. package/dist/internal/asn1/der.d.ts +1 -2
  19. package/dist/internal/asn1/der.js.map +1 -1
  20. package/dist/internal/asn1/oids.js +71 -353
  21. package/dist/internal/asn1/oids.js.map +1 -1
  22. package/dist/internal/asn1/oids.json.js +357 -0
  23. package/dist/internal/asn1/oids.json.js.map +1 -0
  24. package/dist/internal/crypto/algorithm-names.js +1 -1
  25. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  26. package/dist/internal/crypto/ecdsa.js.map +1 -1
  27. package/dist/internal/crypto/hash.js.map +1 -1
  28. package/dist/internal/crypto/pbes2.d.ts +1 -2
  29. package/dist/internal/crypto/pbes2.js +70 -70
  30. package/dist/internal/crypto/pbes2.js.map +1 -1
  31. package/dist/internal/crypto/prime-ec.js +37 -0
  32. package/dist/internal/crypto/prime-ec.js.map +1 -0
  33. package/dist/internal/crypto/rsa-pss.js +50 -50
  34. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  35. package/dist/internal/crypto/sig-verify.d.ts +41 -2
  36. package/dist/internal/crypto/sig-verify.js +125 -38
  37. package/dist/internal/crypto/sig-verify.js.map +1 -1
  38. package/dist/internal/crypto/signing.d.ts +1 -2
  39. package/dist/internal/crypto/signing.js +26 -26
  40. package/dist/internal/crypto/signing.js.map +1 -1
  41. package/dist/internal/jose/base64url.js.map +1 -1
  42. package/dist/internal/jose/json-data.js +108 -0
  43. package/dist/internal/jose/json-data.js.map +1 -0
  44. package/dist/internal/jose/strict-json.d.ts +1 -2
  45. package/dist/internal/jose/strict-json.js.map +1 -1
  46. package/dist/internal/shared/base64.js.map +1 -1
  47. package/dist/internal/shared/dn.d.ts +1 -2
  48. package/dist/internal/shared/dn.js +1 -1
  49. package/dist/internal/shared/dn.js.map +1 -1
  50. package/dist/internal/shared/idna.js.map +1 -1
  51. package/dist/internal/shared/ip.d.ts +1 -2
  52. package/dist/internal/shared/ip.js.map +1 -1
  53. package/dist/internal/shared/mailbox.js.map +1 -1
  54. package/dist/internal/shared/punycode.js.map +1 -1
  55. package/dist/internal/shared/uri-host.js.map +1 -1
  56. package/dist/internal/verify/name-constraints-engine.js +64 -64
  57. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  58. package/dist/internal/verify/policy-engine.js +1 -1
  59. package/dist/internal/verify/policy-engine.js.map +1 -1
  60. package/dist/internal/verify/spki-distrust.js.map +1 -1
  61. package/dist/internal/verify/verify-path.d.ts +1 -2
  62. package/dist/internal/verify/verify-path.js +234 -128
  63. package/dist/internal/verify/verify-path.js.map +1 -1
  64. package/dist/internal/x509/directory-name.js +10 -10
  65. package/dist/internal/x509/directory-name.js.map +1 -1
  66. package/dist/internal/x509/extension-bits.js.map +1 -1
  67. package/dist/internal/x509/extension-errors.d.ts +1 -2
  68. package/dist/internal/x509/extension-errors.js.map +1 -1
  69. package/dist/internal/x509/extension-registry.js +18 -18
  70. package/dist/internal/x509/extension-registry.js.map +1 -1
  71. package/dist/internal/x509/general-name-profile.js +9 -9
  72. package/dist/internal/x509/general-name-profile.js.map +1 -1
  73. package/dist/internal/x509/general-name.js +32 -32
  74. package/dist/internal/x509/general-name.js.map +1 -1
  75. package/dist/internal/x509/name-fields.js +1 -1
  76. package/dist/internal/x509/name-fields.js.map +1 -1
  77. package/dist/internal/x509/or-address.js.map +1 -1
  78. package/dist/jose/base64url.d.ts +4 -0
  79. package/dist/jose/base64url.js +14 -0
  80. package/dist/jose/base64url.js.map +1 -0
  81. package/dist/jose/errors.d.ts +9 -3
  82. package/dist/jose/errors.js.map +1 -1
  83. package/dist/jose/jwe.d.ts +64 -0
  84. package/dist/jose/jwe.js +188 -0
  85. package/dist/jose/jwe.js.map +1 -0
  86. package/dist/jose/jwks.d.ts +38 -10
  87. package/dist/jose/jwks.js +156 -96
  88. package/dist/jose/jwks.js.map +1 -1
  89. package/dist/jose/jws.d.ts +8 -6
  90. package/dist/jose/jws.js +216 -170
  91. package/dist/jose/jws.js.map +1 -1
  92. package/dist/jose/jwt.d.ts +8 -2
  93. package/dist/jose/jwt.js +98 -98
  94. package/dist/jose/jwt.js.map +1 -1
  95. package/dist/jose/remote-jwks.d.ts +1 -2
  96. package/dist/jose/remote-jwks.js +106 -108
  97. package/dist/jose/remote-jwks.js.map +1 -1
  98. package/dist/jose.d.ts +15 -4
  99. package/dist/jose.js +7 -5
  100. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  101. package/dist/kdf/argon2-core.js.map +1 -1
  102. package/dist/kdf/argon2-memory.js.map +1 -1
  103. package/dist/kdf/argon2-portable.js.map +1 -1
  104. package/dist/kdf/argon2.d.ts +7 -2
  105. package/dist/kdf/argon2.js.map +1 -1
  106. package/dist/kdf.d.ts +6 -0
  107. package/dist/keys/keys.d.ts +31 -6
  108. package/dist/keys/keys.js +315 -233
  109. package/dist/keys/keys.js.map +1 -1
  110. package/dist/keys.d.ts +11 -2
  111. package/dist/keys.js +2 -2
  112. package/dist/pem/pem.d.ts +1 -2
  113. package/dist/pem/pem.js +40 -25
  114. package/dist/pem/pem.js.map +1 -1
  115. package/dist/pem.d.ts +6 -0
  116. package/dist/pkcs/pfx.d.ts +2 -3
  117. package/dist/pkcs/pfx.js +142 -142
  118. package/dist/pkcs/pfx.js.map +1 -1
  119. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  120. package/dist/pkcs/pkcs12-mac.js +122 -122
  121. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  122. package/dist/pkcs/pkcs7.d.ts +24 -3
  123. package/dist/pkcs/pkcs7.js +294 -256
  124. package/dist/pkcs/pkcs7.js.map +1 -1
  125. package/dist/pkcs.d.ts +10 -1
  126. package/dist/pkcs.js +4 -4
  127. package/dist/result/result.d.ts +1 -2
  128. package/dist/result/result.js.map +1 -1
  129. package/dist/result.d.ts +6 -0
  130. package/dist/revocation/chain.d.ts +69 -16
  131. package/dist/revocation/chain.js +431 -303
  132. package/dist/revocation/chain.js.map +1 -1
  133. package/dist/revocation/crl.d.ts +67 -14
  134. package/dist/revocation/crl.js +656 -366
  135. package/dist/revocation/crl.js.map +1 -1
  136. package/dist/revocation/ocsp.d.ts +78 -24
  137. package/dist/revocation/ocsp.js +622 -436
  138. package/dist/revocation/ocsp.js.map +1 -1
  139. package/dist/revocation/revocation.d.ts +68 -14
  140. package/dist/revocation/revocation.js +195 -74
  141. package/dist/revocation/revocation.js.map +1 -1
  142. package/dist/revocation.d.ts +14 -5
  143. package/dist/revocation.js +4 -4
  144. package/dist/ssh/ssh.d.ts +2 -3
  145. package/dist/ssh/ssh.js +165 -170
  146. package/dist/ssh/ssh.js.map +1 -1
  147. package/dist/ssh/wire.d.ts +1 -2
  148. package/dist/ssh/wire.js +10 -10
  149. package/dist/ssh/wire.js.map +1 -1
  150. package/dist/ssh.d.ts +8 -0
  151. package/dist/verify/identity.d.ts +3 -4
  152. package/dist/verify/identity.js +33 -33
  153. package/dist/verify/identity.js.map +1 -1
  154. package/dist/verify/name-constraints.d.ts +9 -2
  155. package/dist/verify/policy.d.ts +9 -2
  156. package/dist/verify/verify.d.ts +85 -34
  157. package/dist/verify/verify.js +276 -226
  158. package/dist/verify/verify.js.map +1 -1
  159. package/dist/verify.d.ts +12 -2
  160. package/dist/x509/certificate.d.ts +4 -5
  161. package/dist/x509/certificate.js +40 -40
  162. package/dist/x509/certificate.js.map +1 -1
  163. package/dist/x509/csr.d.ts +3 -4
  164. package/dist/x509/csr.js +15 -15
  165. package/dist/x509/csr.js.map +1 -1
  166. package/dist/x509/extensions.d.ts +1 -2
  167. package/dist/x509/extensions.js +165 -165
  168. package/dist/x509/extensions.js.map +1 -1
  169. package/dist/x509/fingerprint.d.ts +1 -2
  170. package/dist/x509/fingerprint.js.map +1 -1
  171. package/dist/x509/name-text.d.ts +1 -2
  172. package/dist/x509/name-text.js.map +1 -1
  173. package/dist/x509/name.d.ts +1 -2
  174. package/dist/x509/name.js +15 -15
  175. package/dist/x509/name.js.map +1 -1
  176. package/dist/x509/parse.d.ts +9 -6
  177. package/dist/x509/parse.js +394 -394
  178. package/dist/x509/parse.js.map +1 -1
  179. package/dist/x509.d.ts +17 -4
  180. package/dist/x509.js +8 -8
  181. package/package.json +32 -33
  182. package/dist/internal/asn1/oids2.js +0 -75
  183. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -1 +1 @@
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,GAAi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","berPrimitiveContent","berSequenceChildren","berStringContent","berToDefiniteLength","readBerRoot","DECODE_LIMIT_CODES","decodeRefusalOf","bmpString","explicitContext","integerFromNumber","objectIdentifier","octetString","readElement","readRootElement","sequence","setOf","tlv","OIDS","createKdfBudget","decryptPbes2","encryptPbes2","isKdfIterationLimitError","isWrongPasswordError","base64Encode","exportPkcs8Der","pemEncode","splitPemBlocksOrThrow","createPkcs12MacData","parsePkcs12MacData","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","throwMicro509Error","parseCertificateDerOrThrow","input","certificateBags","privateKeyBags","certificate","certificateDer","privateKey","contentInfos","safeContents","authenticatedSafe","macData","der","code","message","options","budget","topLevel","version","authSafe","authenticatedSafeOctets","macElement","macResult","bags","contentInfo","safeContentsResult","bag","error","refusal","pem","bytes","blocks","block","source","oid","content","children","contentType","data","encryptedData","decrypted","root","attributes","certBag","pkcs8Der","encryption","out","friendlyName","bagId","bagValue","attributeSet","bagOid","value","certBagChildren","certType","certValue","entries","localKeyId","attribute","parts","values","attrOid","rawValues","firstValue","element","candidate","macDataDer","password","encryptedContentInfo","contentInfoChildren","algorithm","encryptedContent","child"],"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,UAAUuC,GAAiD;CAChF,IAAMC,IAAgC,CAAC,GACjCC,IAA+B,CAAC;CACtC,KAAK,IAAMC,KAAeH,EAAM,gBAAgB,CAAC,GAAG;EAGnD,IAAII;EACJ,IAAI;GACHA,IAAiB,qBAAqBD,EAAY,WAAW;EAC9D,QAAQ;GACP,OAAO,mBACN,uBACA,qEACD;EACD;EACAF,EAAgB,KAAK,qBAAqBG,GAAgBD,EAAY,UAAU,CAAC;CAClF;CACA,KAAK,IAAME,KAAcL,EAAM,eAAe,CAAC,GAC9CE,EAAe,KACd,oBAAoB,MAAM,oBAAoBG,EAAW,UAAU,GAAGA,EAAW,UAAU,CAC5F;CAED,IAAMC,IAA6B,CAAC;CAIpC,IAHIL,EAAgB,SAAS,KAC5BK,EAAa,KAAK,sBAAsB1B,EAASqB,CAAe,CAAC,CAAC,GAE/DC,EAAe,SAAS,GAAG;EAC9B,IAAMK,IAAe3B,EAASsB,CAAc;EAC5CI,EAAa,KACZN,EAAM,eAAe,KAAA,IAClB,sBAAsBO,CAAY,IAClC,MAAM,+BAA+BA,GAAcP,EAAM,UAAU,CACvE;CACD;CACA,IAAMQ,IAAoB5B,EAAS0B,CAAY,GACzCG,IACLT,EAAM,QAAQ,KAAA,IAAY,KAAA,IAAY,MAAMP,EAAoBe,GAAmB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+D,GAAQ,oBAAoB+B,CAAO,GAAG,CAAI;AACnE;;AAGA,SAAS,oBAAoBA,GAAiC;CAC7D,IAAIA,EAAQ,QAAQ,KACnB,MAAU,MAAM,6BAA6B;CAE9C,IAAMQ,IAAQR,EAAQ,SAAS;CAC/B,IAAIA,EAAQ,SAAS,WAAW,KAAKQ,MAAU,KAAA,GAC9C,MAAU,MAAM,0DAA0D;CAE3E,OAAOA;AACR;;AAGA,SAAS,mBAAmB5D,GAAyB;CACpD,IAAMoD,IAAUpF,EAAYgC,CAAG;CAC/B,IAAIoD,EAAQ,QAAQ,IACnB,MAAU,MAAM,kCAAkC;CAEnD,IAAMjB,IAAelF,EAAa,IAAMmG,EAAQ,KAAK;CACrD,IAAIjB,EAAa,SAAS,KAAKA,EAAa,SAAS,KACpD,MAAU,MAAM,4CAA4C;CAE7D,OAAOA;AACR"}
@@ -140,5 +140,4 @@ export declare function parsePkcs12MacDataOrThrow(der: Uint8Array, authenticated
140
140
  * {@linkcode Number.MAX_SAFE_INTEGER} is `'malformed'`, and `verification` is
141
141
  * `'unchecked'`. For the throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
142
142
  */
143
- export declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string, options?: ParsePkcs12MacDataOptions): Promise<ParsePkcs12MacDataResult>;
144
- //# sourceMappingURL=pkcs12-mac.d.ts.map
143
+ export declare function parsePkcs12MacData(der: Uint8Array, authenticatedSafe: Uint8Array, password?: string, options?: ParsePkcs12MacDataOptions): Promise<ParsePkcs12MacDataResult>;
@@ -1,11 +1,11 @@
1
- import { failureResult as e, isResultError as t, rethrowIfInvariant as n, successResult as r, throwMicro509Error as i } from "../result/result.js";
2
- import { DECODE_LIMIT_CODES as a, decodeFailureResult as o } from "../internal/asn1/decode-refusal.js";
3
- import { concatBytes as s, integerFromNumber as c, nullValue as l, objectIdentifier as u, octetString as d, readSequenceChildren as f, sequence as p } from "../internal/asn1/der.js";
4
- import { decodeIntegerMagnitude as m, decodeObjectIdentifier as h, toArrayBuffer as g, toHex as _ } from "../internal/asn1/asn1.js";
5
- import { OIDS as v } from "../internal/asn1/oids2.js";
6
- import { getCrypto as y } from "../internal/crypto/webcrypto.js";
7
- import { DEFAULT_MAX_KDF_ITERATIONS as b, DEFAULT_MAX_PKCS12_MAC_ITERATIONS as x, WEBCRYPTO_MAX_PBKDF2_ITERATIONS as S, chargeKdfBudget as C, createKdfBudget as w, derivePbkdf2Bytes as T, isKdfIterationLimitError as E } from "../internal/crypto/pbes2.js";
8
- import { describeHashAlgorithm as D } from "../internal/crypto/algorithm-names.js";
1
+ import { decodeIntegerMagnitude as e, decodeObjectIdentifier as t, toArrayBuffer as n, toHex as r } from "../internal/asn1/asn1.js";
2
+ import { DECODE_LIMIT_CODES as i, decodeFailureResult as a } from "../internal/asn1/decode-refusal.js";
3
+ import { concatBytes as o, integerFromNumber as s, nullValue as c, objectIdentifier as l, octetString as u, readSequenceChildren as d, sequence as f } from "../internal/asn1/der.js";
4
+ import { OIDS as p } from "../internal/asn1/oids.js";
5
+ import { describeHashAlgorithm as m } from "../internal/crypto/algorithm-names.js";
6
+ import { DEFAULT_MAX_KDF_ITERATIONS as h, DEFAULT_MAX_PKCS12_MAC_ITERATIONS as g, WEBCRYPTO_MAX_PBKDF2_ITERATIONS as _, chargeKdfBudget as v, createKdfBudget as y, derivePbkdf2Bytes as b, isKdfIterationLimitError as x } from "../internal/crypto/pbes2.js";
7
+ import { getCrypto as S } from "../internal/crypto/webcrypto.js";
8
+ import { failureResult as C, isResultError as w, rethrowIfInvariant as T, successResult as E, throwMicro509Error as D } from "../result/result.js";
9
9
  // src/pkcs/pkcs12-mac.ts
10
10
  /**
11
11
  * PKCS#12 MAC data creation and verification.
@@ -17,7 +17,7 @@ import { describeHashAlgorithm as D } from "../internal/crypto/algorithm-names.j
17
17
  * @module
18
18
  */
19
19
  function throwPkcs12MacError(e, t) {
20
- i(e, t);
20
+ D(e, t);
21
21
  }
22
22
  /**
23
23
  * Computes a PKCS#12 MAC over the AuthenticatedSafe and returns the DER-encoded MacData
@@ -32,19 +32,19 @@ async function createPkcs12MacData(e, t) {
32
32
  if (t.type === "pbmac1") return await createPbmac1MacData(e, t);
33
33
  let n = t.iterations ?? 2048;
34
34
  (!Number.isSafeInteger(n) || n <= 0) && throwPkcs12MacError("invalid_iterations", `MacData iterations must be a positive safe integer, got ${n}`);
35
- let r = t.salt ?? y().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), i = await computePkcs12Mac(e, t.password, r, n);
35
+ let i = t.salt ?? S().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), a = await computePkcs12Mac(e, t.password, i, n);
36
36
  return {
37
- der: p([
38
- p([p([u(v.sha256), l()]), d(i)]),
39
- d(r),
40
- ...n === 1 ? [] : [c(n)]
37
+ der: f([
38
+ f([f([l(p.sha256), c()]), u(a)]),
39
+ u(i),
40
+ ...n === 1 ? [] : [s(n)]
41
41
  ]),
42
42
  parsed: {
43
43
  type: "pkcs12-kdf",
44
- digestAlgorithmOid: v.sha256,
45
- digestAlgorithmName: D(v.sha256),
46
- digestHex: _(i),
47
- saltHex: _(r),
44
+ digestAlgorithmOid: p.sha256,
45
+ digestAlgorithmName: m(p.sha256),
46
+ digestHex: r(a),
47
+ saltHex: r(i),
48
48
  iterations: n,
49
49
  verification: "valid"
50
50
  }
@@ -52,31 +52,31 @@ async function createPkcs12MacData(e, t) {
52
52
  }
53
53
  async function createPbmac1MacData(e, t) {
54
54
  let n = t.iterations ?? 1e5;
55
- (!Number.isInteger(n) || n < 1 || n > 4294967295) && throwPkcs12MacError("invalid_iterations", `PBMAC1 iterations must be an integer from 1 to ${S}, got ${n}`);
56
- let r = t.salt ?? y().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), i = {
57
- salt: r,
55
+ (!Number.isInteger(n) || n < 1 || n > 4294967295) && throwPkcs12MacError("invalid_iterations", `PBMAC1 iterations must be an integer from 1 to ${_}, got ${n}`);
56
+ let i = t.salt ?? S().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), a = {
57
+ salt: i,
58
58
  iterations: n,
59
59
  keyLength: 32,
60
60
  prf: "HMAC-SHA-256",
61
61
  messageAuthScheme: "HMAC-SHA-256"
62
- }, a = await computePbmac1(e, t.password, i), o = p([u(v.hmacWithSHA256), l()]), s = p([u(v.pbmac1), p([p([u(v.pbkdf2), p([
63
- d(r),
64
- c(n),
65
- c(i.keyLength),
66
- o
67
- ])]), o])]);
62
+ }, o = await computePbmac1(e, t.password, a), d = f([l(p.hmacWithSHA256), c()]), m = f([l(p.pbmac1), f([f([l(p.pbkdf2), f([
63
+ u(i),
64
+ s(n),
65
+ s(a.keyLength),
66
+ d
67
+ ])]), d])]);
68
68
  return {
69
- der: p([p([s, d(a)]), d(r)]),
69
+ der: f([f([m, u(o)]), u(i)]),
70
70
  parsed: {
71
71
  type: "pbmac1",
72
- digestAlgorithmOid: v.pbmac1,
72
+ digestAlgorithmOid: p.pbmac1,
73
73
  digestAlgorithmName: "PBMAC1",
74
- digestHex: _(a),
75
- saltHex: _(r),
74
+ digestHex: r(o),
75
+ saltHex: r(i),
76
76
  iterations: n,
77
- keyLength: i.keyLength,
78
- prf: i.prf,
79
- messageAuthScheme: i.messageAuthScheme,
77
+ keyLength: a.keyLength,
78
+ prf: a.prf,
79
+ messageAuthScheme: a.messageAuthScheme,
80
80
  verification: "valid"
81
81
  }
82
82
  };
@@ -88,7 +88,7 @@ const O = [
88
88
  "weak_mac_key_length"
89
89
  ];
90
90
  function throwMacDataError(e, t) {
91
- i(e, t);
91
+ D(e, t);
92
92
  }
93
93
  /**
94
94
  * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is
@@ -102,33 +102,33 @@ function throwMacDataError(e, t) {
102
102
  * {@linkcode ParsePkcs12MacDataErrorCode} for an unsupported MAC, a PBMAC1 key
103
103
  * length below 20 octets, or a password the MAC cannot encode.
104
104
  */
105
- async function parsePkcs12MacDataOrThrow(e, t, n, r) {
106
- let i = w(r, x), a = w(r, b), o = f(e), s = o[0], c = o[1], l = o[2];
107
- if (o.length !== 2 && o.length !== 3 || s === void 0 || c === void 0 || c.tag !== 4 || l !== void 0 && l.tag !== 2) throw Error("Malformed MacData");
108
- let u = e.slice(s.start - s.headerLength, s.end), d = f(u), p = d[0], m = d[1];
109
- if (d.length !== 2 || p === void 0 || m === void 0 || m.tag !== 4) throw Error("Malformed DigestInfo");
110
- let g = u.slice(p.start - p.headerLength, p.end), y = f(g), S = y[0];
111
- if (S === void 0 || y.length !== 1 && y.length !== 2) throw Error("MacData algorithm missing");
112
- let T = h(S.value);
113
- if (T === v.pbmac1) return await verifyPbmac1MacData(g, y[1], m.value, t, n, a);
114
- T !== v.sha256 && throwMacDataError("unsupported_mac_algorithm", `Only SHA-256 PKCS#12 MAC and PBMAC1 are supported, got ${D(T)}`);
115
- let E = l === void 0 ? 1 : decodeMacIterations(l.value, i, n, "MacData iterations");
116
- if (E === 0) throw Error("MacData iterations must be a positive safe integer");
105
+ async function parsePkcs12MacDataOrThrow(e, n, i, a) {
106
+ let o = y(a, g), s = y(a, h), c = d(e), l = c[0], u = c[1], f = c[2];
107
+ if (c.length !== 2 && c.length !== 3 || l === void 0 || u === void 0 || u.tag !== 4 || f !== void 0 && f.tag !== 2) throw Error("Malformed MacData");
108
+ let _ = e.slice(l.start - l.headerLength, l.end), b = d(_), x = b[0], S = b[1];
109
+ if (b.length !== 2 || x === void 0 || S === void 0 || S.tag !== 4) throw Error("Malformed DigestInfo");
110
+ let C = _.slice(x.start - x.headerLength, x.end), w = d(C), T = w[0];
111
+ if (T === void 0 || w.length !== 1 && w.length !== 2) throw Error("MacData algorithm missing");
112
+ let E = t(T.value);
113
+ if (E === p.pbmac1) return await verifyPbmac1MacData(C, w[1], S.value, n, i, s);
114
+ E !== p.sha256 && throwMacDataError("unsupported_mac_algorithm", `Only SHA-256 PKCS#12 MAC and PBMAC1 are supported, got ${m(E)}`);
115
+ let D = f === void 0 ? 1 : decodeMacIterations(f.value, o, i, "MacData iterations");
116
+ if (D === 0) throw Error("MacData iterations must be a positive safe integer");
117
117
  let O = {
118
118
  type: "pkcs12-kdf",
119
- digestAlgorithmOid: T,
120
- digestAlgorithmName: D(T),
121
- digestHex: _(m.value),
122
- saltHex: _(c.value),
123
- iterations: E,
119
+ digestAlgorithmOid: E,
120
+ digestAlgorithmName: m(E),
121
+ digestHex: r(S.value),
122
+ saltHex: r(u.value),
123
+ iterations: D,
124
124
  verification: "unchecked"
125
125
  };
126
- if (n === void 0) return O;
127
- C(i, E);
128
- let k = await computePkcs12Mac(t, n, c.value, E);
126
+ if (i === void 0) return O;
127
+ v(o, D);
128
+ let k = await computePkcs12Mac(n, i, u.value, D);
129
129
  return {
130
130
  ...O,
131
- verification: equalBytes(k, m.value) ? "valid" : "invalid"
131
+ verification: equalBytes(k, S.value) ? "valid" : "invalid"
132
132
  };
133
133
  }
134
134
  /**
@@ -150,97 +150,97 @@ async function parsePkcs12MacDataOrThrow(e, t, n, r) {
150
150
  * {@linkcode Number.MAX_SAFE_INTEGER} is `'malformed'`, and `verification` is
151
151
  * `'unchecked'`. For the throwing form use {@linkcode parsePkcs12MacDataOrThrow}.
152
152
  */
153
- async function parsePkcs12MacData(i, s, c, l) {
153
+ async function parsePkcs12MacData(e, t, n, r) {
154
154
  try {
155
- return r(await parsePkcs12MacDataOrThrow(i, s, c, l));
156
- } catch (r) {
157
- if (n(r), E(r)) return e("kdf_iterations_exceeded", r.message);
158
- if (t(r)) {
159
- let t = O.find((e) => e === r.code);
160
- if (t !== void 0) return e(t, r.error.message);
155
+ return E(await parsePkcs12MacDataOrThrow(e, t, n, r));
156
+ } catch (e) {
157
+ if (T(e), x(e)) return C("kdf_iterations_exceeded", e.message);
158
+ if (w(e)) {
159
+ let t = O.find((t) => t === e.code);
160
+ if (t !== void 0) return C(t, e.error.message);
161
161
  }
162
- return o(r, a, "Malformed MacData");
162
+ return a(e, i, "Malformed MacData");
163
163
  }
164
164
  }
165
- function decodeMacIterations(e, t, n, r) {
166
- let i = m(e, r);
167
- if (i.type === "safe") return i.value;
168
- throw n !== void 0 && C(t, Infinity), Error(`${r} too large for safe number (${e.length} bytes)`);
165
+ function decodeMacIterations(t, n, r, i) {
166
+ let a = e(t, i);
167
+ if (a.type === "safe") return a.value;
168
+ throw r !== void 0 && v(n, 1e400), Error(`${i} too large for safe number (${t.length} bytes)`);
169
169
  }
170
- async function verifyPbmac1MacData(e, t, n, r, i, a) {
170
+ async function verifyPbmac1MacData(e, t, n, i, a, o) {
171
171
  if (t === void 0) throw Error("PBMAC1 parameters must be present");
172
- let o = parsePbmac1Parameters(e, t), s = {
172
+ let s = parsePbmac1Parameters(e, t), c = {
173
173
  type: "pbmac1",
174
- digestAlgorithmOid: v.pbmac1,
174
+ digestAlgorithmOid: p.pbmac1,
175
175
  digestAlgorithmName: "PBMAC1",
176
- digestHex: _(n),
177
- saltHex: _(o.salt),
178
- iterations: o.iterations,
179
- keyLength: o.keyLength,
180
- prf: o.prf,
181
- messageAuthScheme: o.messageAuthScheme,
176
+ digestHex: r(n),
177
+ saltHex: r(s.salt),
178
+ iterations: s.iterations,
179
+ keyLength: s.keyLength,
180
+ prf: s.prf,
181
+ messageAuthScheme: s.messageAuthScheme,
182
182
  verification: "unchecked"
183
183
  };
184
- if (i === void 0) return s;
185
- C(a, o.iterations);
186
- let c = await computePbmac1(r, i, o);
184
+ if (a === void 0) return c;
185
+ v(o, s.iterations);
186
+ let l = await computePbmac1(i, a, s);
187
187
  return {
188
- ...s,
189
- verification: equalBytes(c, n) ? "valid" : "invalid"
188
+ ...c,
189
+ verification: equalBytes(l, n) ? "valid" : "invalid"
190
190
  };
191
191
  }
192
192
  function parsePbmac1Parameters(e, t) {
193
193
  if (t.tag !== 48) throw Error("Malformed PBMAC1-params");
194
- let n = e.slice(t.start - t.headerLength, t.end), r = f(n), i = r[0], a = r[1];
194
+ let n = e.slice(t.start - t.headerLength, t.end), r = d(n), i = r[0], a = r[1];
195
195
  if (r.length !== 2 || i === void 0 || a === void 0) throw Error("Malformed PBMAC1-params");
196
196
  let o = readAlgorithmIdentifier(n, i, "PBMAC1 keyDerivationFunc");
197
- o.oid !== v.pbkdf2 && throwMacDataError("unsupported_mac_algorithm", `Unsupported PBMAC1 key derivation function ${o.oid}`);
197
+ o.oid !== p.pbkdf2 && throwMacDataError("unsupported_mac_algorithm", `Unsupported PBMAC1 key derivation function ${o.oid}`);
198
198
  let s = parseHmacAlgorithm(readAlgorithmIdentifier(n, a, "PBMAC1 messageAuthScheme"), "PBMAC1 messageAuthScheme");
199
199
  return {
200
200
  ...parsePbkdf2Parameters(o),
201
201
  messageAuthScheme: s
202
202
  };
203
203
  }
204
- function parsePbkdf2Parameters(e) {
205
- if (e.parameters === void 0 || e.parameters.tag !== 48) throw Error("Malformed PBKDF2-params");
206
- let t = e.der.slice(e.parameters.start - e.parameters.headerLength, e.parameters.end), [n, r, ...i] = f(t);
207
- if (n === void 0 || r === void 0 || r.tag !== 2) throw Error("Malformed PBKDF2-params");
208
- if (n.tag === 48 && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 otherSource salt is not supported"), n.tag !== 4) throw Error("Malformed PBKDF2 salt");
209
- let a = i[0]?.tag === 2 ? i[0] : void 0, o = a === void 0 ? i : i.slice(1), s = o[0];
210
- if (o.length > 1 || s !== void 0 && s.tag !== 48) throw Error("Malformed PBKDF2-params");
211
- if (a === void 0) throw Error("PBKDF2-params in PBMAC1 must include keyLength");
212
- s === void 0 && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 prf is absent and defaults to HMAC-SHA-1, which PBMAC1 verification does not accept");
213
- let c = parseHmacAlgorithm(readAlgorithmIdentifier(t, s, "PBKDF2 prf"), "PBKDF2 prf"), l = m(r.value, "PBKDF2 iterationCount");
214
- if (l.type === "unsafe" || l.value > 4294967295) throw Error(`PBKDF2 iterationCount must be at most ${S}`);
215
- if (l.value === 0) throw Error("PBKDF2 iterationCount must be at least 1");
204
+ function parsePbkdf2Parameters(t) {
205
+ if (t.parameters === void 0 || t.parameters.tag !== 48) throw Error("Malformed PBKDF2-params");
206
+ let n = t.der.slice(t.parameters.start - t.parameters.headerLength, t.parameters.end), [r, i, ...a] = d(n);
207
+ if (r === void 0 || i === void 0 || i.tag !== 2) throw Error("Malformed PBKDF2-params");
208
+ if (r.tag === 48 && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 otherSource salt is not supported"), r.tag !== 4) throw Error("Malformed PBKDF2 salt");
209
+ let o = a[0]?.tag === 2 ? a[0] : void 0, s = o === void 0 ? a : a.slice(1), c = s[0];
210
+ if (s.length > 1 || c !== void 0 && c.tag !== 48) throw Error("Malformed PBKDF2-params");
211
+ if (o === void 0) throw Error("PBKDF2-params in PBMAC1 must include keyLength");
212
+ c === void 0 && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 prf is absent and defaults to HMAC-SHA-1, which PBMAC1 verification does not accept");
213
+ let l = parseHmacAlgorithm(readAlgorithmIdentifier(n, c, "PBKDF2 prf"), "PBKDF2 prf"), u = e(i.value, "PBKDF2 iterationCount");
214
+ if (u.type === "unsafe" || u.value > 4294967295) throw Error(`PBKDF2 iterationCount must be at most ${_}`);
215
+ if (u.value === 0) throw Error("PBKDF2 iterationCount must be at least 1");
216
216
  return {
217
- salt: new Uint8Array(n.value),
218
- iterations: l.value,
219
- keyLength: decodePbmac1KeyLength(a.value),
220
- prf: c
217
+ salt: new Uint8Array(r.value),
218
+ iterations: u.value,
219
+ keyLength: decodePbmac1KeyLength(o.value),
220
+ prf: l
221
221
  };
222
222
  }
223
- function decodePbmac1KeyLength(e) {
224
- let t = m(e, "PBKDF2 keyLength");
225
- if ((t.type === "unsafe" || t.value > 64) && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 keyLength above 64 octets is not supported"), t.value === 0) throw Error("PBKDF2 keyLength must be at least 1");
226
- return t.value < 20 && throwMacDataError("weak_mac_key_length", `PBKDF2 keyLength ${t.value} is below 20 octets`), t.value;
223
+ function decodePbmac1KeyLength(t) {
224
+ let n = e(t, "PBKDF2 keyLength");
225
+ if ((n.type === "unsafe" || n.value > 64) && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 keyLength above 64 octets is not supported"), n.value === 0) throw Error("PBKDF2 keyLength must be at least 1");
226
+ return n.value < 20 && throwMacDataError("weak_mac_key_length", `PBKDF2 keyLength ${n.value} is below 20 octets`), n.value;
227
227
  }
228
- function readAlgorithmIdentifier(e, t, n) {
229
- if (t.tag !== 48) throw Error(`Malformed ${n}`);
230
- let r = e.slice(t.start - t.headerLength, t.end), i = f(r), a = i[0];
231
- if (a === void 0 || a.tag !== 6 || i.length > 2) throw Error(`Malformed ${n}`);
228
+ function readAlgorithmIdentifier(e, n, r) {
229
+ if (n.tag !== 48) throw Error(`Malformed ${r}`);
230
+ let i = e.slice(n.start - n.headerLength, n.end), a = d(i), o = a[0];
231
+ if (o === void 0 || o.tag !== 6 || a.length > 2) throw Error(`Malformed ${r}`);
232
232
  return {
233
- oid: h(a.value),
234
- parameters: i[1],
235
- der: r
233
+ oid: t(o.value),
234
+ parameters: a[1],
235
+ der: i
236
236
  };
237
237
  }
238
238
  function parseHmacAlgorithm(e, t) {
239
239
  if (e.parameters !== void 0 && (e.parameters.tag !== 5 || e.parameters.length !== 0)) throw Error(`${t} parameters must be NULL`);
240
240
  switch (e.oid) {
241
- case v.hmacWithSHA256: return "HMAC-SHA-256";
242
- case v.hmacWithSHA384: return "HMAC-SHA-384";
243
- case v.hmacWithSHA512: return "HMAC-SHA-512";
241
+ case p.hmacWithSHA256: return "HMAC-SHA-256";
242
+ case p.hmacWithSHA384: return "HMAC-SHA-384";
243
+ case p.hmacWithSHA512: return "HMAC-SHA-512";
244
244
  }
245
245
  return throwMacDataError("unsupported_mac_algorithm", `Unsupported ${t} ${e.oid}`);
246
246
  }
@@ -253,7 +253,7 @@ function hmacHash(e) {
253
253
  }
254
254
  }
255
255
  async function computePbmac1(e, t, n) {
256
- return await hmac(e, await T(encodePbmac1Password(t), n.salt, n.iterations, hmacHash(n.prf), n.keyLength), hmacHash(n.messageAuthScheme));
256
+ return await hmac(e, await b(encodePbmac1Password(t), n.salt, n.iterations, hmacHash(n.prf), n.keyLength), hmacHash(n.messageAuthScheme));
257
257
  }
258
258
  function encodePbmac1Password(e) {
259
259
  for (let t = 0; t < e.length; t += 1) {
@@ -273,12 +273,12 @@ function encodePbmac1Password(e) {
273
273
  async function computePkcs12Mac(e, t, n, r) {
274
274
  return await hmac(e, await derivePkcs12Key(t, n, r, 3, 32), "SHA-256");
275
275
  }
276
- async function hmac(e, t, n) {
277
- let r = await y().subtle.importKey("raw", g(t), {
276
+ async function hmac(e, t, r) {
277
+ let i = await S().subtle.importKey("raw", n(t), {
278
278
  name: "HMAC",
279
- hash: n
279
+ hash: r
280
280
  }, !1, ["sign"]);
281
- return new Uint8Array(await y().subtle.sign("HMAC", r, g(e)));
281
+ return new Uint8Array(await S().subtle.sign("HMAC", i, n(e)));
282
282
  }
283
283
  /**
284
284
  * PKCS#12 key derivation with SHA-256 (RFC 7292 Appendix B). `id` selects the purpose:
@@ -288,9 +288,9 @@ async function hmac(e, t, n) {
288
288
  * UTF-16 surrogate, U+FFFE or U+FFFF.
289
289
  */
290
290
  async function derivePkcs12Key(e, t, n, r, i) {
291
- let a = (/* @__PURE__ */ new Uint8Array(64)).fill(r), o = encodePkcs12Password(e), c = s([repeatToMultiple(t, 64), repeatToMultiple(o, 64)]), l = Math.ceil(i / 32), u = new Uint8Array(l * 32);
291
+ let a = (/* @__PURE__ */ new Uint8Array(64)).fill(r), s = encodePkcs12Password(e), c = o([repeatToMultiple(t, 64), repeatToMultiple(s, 64)]), l = Math.ceil(i / 32), u = new Uint8Array(l * 32);
292
292
  for (let e = 0; e < l; e += 1) {
293
- let t = await digestSha256(s([a, c]));
293
+ let t = await digestSha256(o([a, c]));
294
294
  for (let e = 1; e < n; e += 1) t = await digestSha256(t);
295
295
  if (u.set(t, e * 32), e + 1 === l) break;
296
296
  let r = repeatToLength(t, 64);
@@ -300,7 +300,7 @@ async function derivePkcs12Key(e, t, n, r, i) {
300
300
  }
301
301
  /** SHA-256 hash via WebCrypto. */
302
302
  async function digestSha256(e) {
303
- return new Uint8Array(await y().subtle.digest("SHA-256", g(e)));
303
+ return new Uint8Array(await S().subtle.digest("SHA-256", n(e)));
304
304
  }
305
305
  /** Encodes a password as a null-terminated BMPString, two big-endian bytes per character (RFC 7292 B.1). */
306
306
  function encodePkcs12Password(e) {