# `SefazNfe.Certificate.PKCS12`
[🔗](https://github.com/devaction-labs/sefaz_nfe/blob/v0.5.0/lib/sefaz_nfe/certificate/pkcs12.ex#L1)

PKCS#12 (RFC 7292) reader for ICP-Brasil A1 files. Internal to
`SefazNfe.Certificate`.

OTP 29 ships no PKCS#12 support — `:public_key` has no `pkcs12_to_der` — and
Hex has no package for it, so the PFX is walked here: the DER structure by
hand, `:crypto` for the ciphers.

## Scope

Supported, each verified byte-for-byte against `openssl` output (and, for the
first, a real A1 file):

  * bag encryption `pbeWithSHAAnd3-KeyTripleDES-CBC` (PKCS#12 KDF, SHA-1) —
    what ICP-Brasil issues today;
  * bag encryption PBES2 (PKCS#5 v2.1) with PBKDF2 and AES-128/192/256-CBC —
    the OpenSSL 3 export default. PBKDF2 PRFs: `hmacWithSHA1`,
    `hmacWithSHA256` and `hmacWithSHA512`;
  * the PKCS#12 MAC with SHA-1 or SHA-256.

Anything else returns `{:error, {:unsupported_pbe, oid}}`, or
`{:error, {:unsupported_mac, oid}}` for another digest, rather than an empty
result that would read as a certificate with no key. Naming the algorithm
matters: reporting a modern PFX as an invalid password would send the caller
hunting for the wrong bug.

The PKCS#12 MAC is required, not optional. Without it a wrong password is
indistinguishable from a corrupt file, and both must fail before any SOAP
call. It is compared in constant time.

## Hostile input

The PFX and the password usually come from a user upload, so nothing in the
file is trusted to size the work. Before any KDF or `:crypto` call:

  * the file is at most 65536 bytes (64 KiB) (a real A1 is about 7 KB) and holds
    at most 32 SafeBags and 32 ContentInfos;
  * every iteration count (MAC, PBES1, PBKDF2) is in `1..1_000_000` (real A1s
    use about 2000), and the sum over the whole file (MAC, PBES1 x3 passes, PBKDF2 x blocks) is at most 2_000_000;
  * a PBKDF2 `keyLength`, when present, equals the cipher's key size;
  * the cipher IV and ciphertext have the sizes the cipher requires.

Violations return `{:error, {:limit_exceeded, :size | :bags | :iterations |
:key_length}}`. Padding is checked strictly (PKCS#7, all pad bytes equal), and
BER indefinite lengths are refused. Any other failure while walking the file
collapses into `{:error, :invalid_certificate}`: `parse/2` rescues everything
and never re-raises or keeps the stacktrace, because a `:crypto` error carries
the derived key or the password in its arguments.

## Key and certificate pairing

A PFX may carry several certificates in any order. The leaf is the one whose
RSA public key equals the one derived from the private key, so a CA listed
first is never mistaken for it. No match is `{:error, :key_cert_mismatch}`,
more than one private key is `{:error, :multiple_keys}` and a non-RSA key is
`{:error, {:unsupported_key, :ec | :other}}`. The chain holds the remaining
certificates, issuer after subject where the names link up.

## Key derivation

`kdf/5` is RFC 7292 appendix B.2 with SHA-1: a 20 byte digest over 64 byte
blocks, diversified by 1 for the key, 2 for the IV and 3 for the MAC
(appendix B.3). The password is a BMPString — UTF-16BE, surrogate pairs outside the
BMP as OpenSSL does, with a two byte null terminator. Each block round is `I_j = (I_j + B + 1) mod 2^512`, where the
modulo falls out of bitstring construction truncating to the declared size.

# `parsed`

```elixir
@type parsed() :: %{der: binary(), key: binary(), chain: [binary()]}
```

# `parse`

```elixir
@spec parse(binary(), String.t()) :: {:ok, parsed()} | {:error, term()}
```

Decodes `pfx` into the leaf certificate, the PKCS#8 private key and the chain.

Errors:

  * `{:error, :invalid_password}` — the MAC does not verify, or `password` is
    not valid UTF-8. A MAC mismatch is indistinguishable from a tampered file,
    but a wrong password is by far the common cause.
  * `{:error, :invalid_certificate}` — anything structurally wrong, however it
    surfaces: it is bad input, never a crash.
  * `{:error, {:limit_exceeded, limit}}` — see the module documentation.
  * `{:error, {:unsupported_pbe, oid}}` / `{:error, {:unsupported_mac, oid}}`.
  * `{:error, :key_cert_mismatch | :multiple_keys | {:unsupported_key, kind}}`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
