# `AshVault.Cipher`
[🔗](https://github.com/jakeschurch/ash_vault/blob/main/lib/ash_vault/cipher.ex#L1)

Behaviour for AEAD ciphers, plus the registry used to resolve a cipher id
read out of a stored envelope.

A cipher is identified by a stable atom id (for example `:aes_256_gcm_v1`) which is
written into every envelope as a binary. Decryption looks the cipher back up through
`fetch/1`, so the cipher a value was encrypted with is always the cipher used to
decrypt it — even if the vault has since been configured with a different default.

Additional ciphers can be registered (binary-keyed, like the built-ins):

    config :ash_vault, :ciphers, %{"my_cipher_v1" => MyApp.Ciphers.Custom}

# `payload`

```elixir
@type payload() :: %{ciphertext: binary(), nonce: binary(), tag: binary()}
```

# `decrypt`

```elixir
@callback decrypt(payload(), key :: AshVault.Key.t(), aad :: binary()) ::
  {:ok, binary()} | {:error, :opaque_key_unsupported} | {:error, term()}
```

Decrypt a payload under `key`, verifying it against `aad`.

Takes the same `AshVault.Key.t()` union as `c:encrypt/3`.

# `encrypt`

```elixir
@callback encrypt(plaintext :: binary(), key :: AshVault.Key.t(), aad :: binary()) ::
  {:ok, payload()} | {:error, :opaque_key_unsupported} | {:error, term()}
```

Encrypt `plaintext` under `key`, binding `aad` into the authentication tag.

`key` is an `AshVault.Key.t()`, which is a raw binary for every cipher and provider
AshVault ships, and may also be an opaque `%AshVault.Key{}` handle to material held
outside the BEAM heap. A cipher that cannot use a handle returns
`{:error, :opaque_key_unsupported}`; it must never fall back to anything else.

# `id`

```elixir
@callback id() :: atom()
```

The stable identifier written into envelopes.

# `key_bytes`

```elixir
@callback key_bytes() :: pos_integer()
```

The exact key size, in bytes, this cipher requires.

# `fetch`

```elixir
@spec fetch(atom() | binary()) :: {:ok, module()} | {:error, Exception.t()}
```

Look up a cipher module by id.

The registry is keyed by the binary id, which is exactly what the envelope stores, so
the encode and decode directions cannot drift. An atom id is converted with
`Atom.to_string/1`; untrusted input is never turned into an atom.

## Examples

    AshVault.Cipher.fetch(:aes_256_gcm_v1)
    #=> {:ok, AshVault.Ciphers.AES.GCM}

    AshVault.Cipher.fetch("aes_256_gcm_v1")
    #=> {:ok, AshVault.Ciphers.AES.GCM}

    AshVault.Cipher.fetch("nope")
    #=> {:error, %AshVault.Errors.UnsupportedCipher{cipher_id: "nope"}}

# `registry`

```elixir
@spec registry() :: %{optional(binary()) =&gt; module()}
```

The full binary-keyed cipher registry: built-in ciphers merged with configured ones.

---

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