# `AshVault.Ciphers.AES.GCM`
[🔗](https://github.com/jakeschurch/ash_vault/blob/main/lib/ash_vault/ciphers/aes_gcm.ex#L1)

AES-256-GCM, the default AshVault cipher.

* 32-byte keys (256 bit)
* 12-byte nonces, freshly generated from `:crypto.strong_rand_bytes/1` per encryption
* 16-byte authentication tags
* the associated data built by `AshVault.Vault.Runtime.build_aad/2` is bound into the
  tag, so a ciphertext only decrypts under the same scope, resource and field

Nonce and tag sizes are deliberately not configurable, and `decrypt/3` **rejects any
payload whose nonce is not 12 bytes or whose tag is not 16 bytes** before the key
touches `:crypto`.

> #### Why the length check is a security control, not a tidiness check {: .error}
>
> `:crypto.crypto_one_time_aead/7` on OTP 29 accepts a truncated GCM tag (verified:
> 1, 2, 4, 8 and 12 bytes all return plaintext; only a 0-byte tag is rejected) and
> compares only the leading N bytes. The AshVault envelope carries `tag_len` as a
> byte read straight out of the database, so an attacker with database write access
> could store a forged row with `tag_len: 1` and enumerate 256 values — GCM is CTR
> mode, so the ciphertext can be XORed to any chosen plaintext first. Success was
> guaranteed within 256 read attempts. Requiring the full 16-byte tag restores the
> 2^-128 forgery bound.

# `decrypt`

```elixir
@spec decrypt(AshVault.Cipher.payload(), AshVault.Key.t(), binary()) ::
  {:ok, binary()} | {:error, term()}
```

Decrypt a payload, verifying the tag against `aad`.

Returns `{:error, :auth_failed}` when the tag does not verify, when the tag is not
exactly 16 bytes, or when the nonce is not exactly 12 bytes; and
`{:error, {:invalid_key_size, n}}` for a key that is not exactly 32 bytes.

The tag and nonce lengths are checked *before* `:crypto` sees them: OTP accepts a
truncated tag and compares only its leading bytes, which turns an attacker-controlled
`tag_len` in the envelope into a ≤256-guess forgery. See the moduledoc.

# `encrypt`

```elixir
@spec encrypt(binary(), AshVault.Key.t(), binary()) ::
  {:ok, AshVault.Cipher.payload()} | {:error, term()}
```

Encrypt `plaintext` with a fresh random nonce.

Returns `{:error, {:invalid_key_size, n}}` if the key is not exactly 32 bytes.

# `id`

```elixir
@spec id() :: :aes_256_gcm_v1
```

The stable cipher id, `:aes_256_gcm_v1`.

# `key_bytes`

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

The required key size in bytes, `32`.

---

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