# `Ecto.Encrypted`
[🔗](https://github.com/elixir-ecto/ecto/blob/v3.15.0/lib/ecto/encrypted.ex#L1)

Defines a type that encrypts values before writing them to the database.

Encryption uses Erlang's `:crypto` module directly and any AEAD cipher
it supports, such as `:aes_256_gcm`, `:aes_128_gcm`, `:aes_256_ccm`,
and `:chacha20_poly1305`.

Each value is encrypted with its own key, derived with HMAC-SHA256
from the configured key and a random salt.

## Usage

First define a module that uses `Ecto.Encrypted` and implements the
`c:keys/0` callback:

    defmodule MyApp.Encrypted do
      use Ecto.Encrypted

      @impl true
      def keys do
        [
          %{
            tag: "v1",
            cipher: :aes_256_gcm,
            key: Application.fetch_env!(:my_app, :encryption_key_v1)
          }
        ]
      end
    end

Now use it as the type of a field:

    schema "users" do
      field :ssn, MyApp.Encrypted, redact: true
    end

The column must be a binary one. In migrations, use `:binary`.

Remember to pass `redact: true` to the field. Otherwise the
decrypted value may show up when inspecting the struct, which
includes logs and error reports.

## Keys

`c:keys/0` returns a list of keys. Each key is a map with the
following fields:

  * `:tag` - a binary of 1 to 255 bytes identifying the key
  * `:cipher` - an AEAD cipher supported by `:crypto`
  * `:key` - the key itself, as a binary

Other fields are ignored.

The first key in the list is used for encryption. All keys can be
used for decryption. The tag is stored as a prefix of each encrypted
value, so we know which key to use when decrypting. The cipher is
never stored, so it can't be chosen by whoever writes to the database.

Keys must be random and have the exact length required by the
cipher, which is 32 bytes for all ciphers above except `:aes_128_gcm`.
You can generate one with:

    $ elixir -e ':crypto.strong_rand_bytes(32) |> Base.encode64() |> IO.puts()'

Then store it in an environment variable and read it in your
`config/runtime.exs`:

    if config_env() == :prod do
      config :my_app,
        encryption_key_v1: Base.decode64!(System.fetch_env!("ENCRYPTION_KEY_V1"))
    end

For development and test, you can set fixed keys in `config/dev.exs`
and `config/test.exs` respectively. Use different keys per environment.
Never store keys in module attributes, as they would then be written to
`.beam` files.

These keys are only for data stored in your database. Do not use
or derive them from secrets shared with other parts of your system,
such as Phoenix's `secret_key_base`. Those secrets may be rotated for
reasons unrelated to your data, and doing so would make all of your
encrypted data unreadable.

## Key and cipher rotation

To rotate keys or change ciphers, add a new key with a new tag to
the beginning of the list:

    def keys do
      [
        %{
          tag: "v2",
          cipher: :chacha20_poly1305,
          key: Application.fetch_env!(:my_app, :encryption_key_v2)
        },
        %{
          tag: "v1",
          cipher: :aes_256_gcm,
          key: Application.fetch_env!(:my_app, :encryption_key_v1)
        }
      ]
    end

New values are encrypted with `"v2"` and existing values are still
decrypted with `"v1"`. You can remove a key once all data encrypted
with it has been re-encrypted.

Loading and saving a struct again does not re-encrypt its data, as
the decrypted value does not change. Use `Ecto.Changeset.force_change/3`
to force the field to be written:

    user
    |> Ecto.Changeset.change()
    |> Ecto.Changeset.force_change(:ssn, user.ssn)
    |> Repo.update!()

## Encoding

By default, only binaries can be encrypted. You can encrypt other
values by implementing the `c:encode/1` and `c:decode/1` callbacks,
plus the `c:Ecto.Type.cast/1` callback to cast external input:

    defmodule MyApp.EncryptedMap do
      use Ecto.Encrypted

      @impl true
      defdelegate keys, to: MyApp.Encrypted

      @impl true
      def cast(value) when is_map(value), do: {:ok, value}
      def cast(_value), do: :error

      @impl true
      def encode(value), do: {:ok, JSON.encode!(value)}

      @impl true
      def decode(binary) do
        case JSON.decode(binary) do
          {:ok, value} -> {:ok, value}
          {:error, _} -> :error
        end
      end
    end

The example above uses the `JSON` module from Elixir v1.18+. As with
the `:map` type, keys are returned as strings after loading.

### Padding

Encryption hides the contents of a value but not its length: the
encrypted value grows with the original one. For fields with few
possible values, such as `"yes"` and `"no"`, the length alone may
reveal the value.

You can hide the length by padding values in `c:encode/1`, so all
values are rounded up to the same size or to multiples of a given
size. Padding is encrypted along with the value and removed in
`c:decode/1`. Since JSON ignores trailing whitespace, padding JSON
only requires changing `c:encode/1` in the example above:

    @impl true
    def encode(value) do
      json = JSON.encode!(value)
      padding = rem(64 - rem(byte_size(json), 64), 64)
      {:ok, json <> :binary.copy(" ", padding)}
    end

For other formats, make sure the padding can always be told apart
from the value. For example, add a `0x80` byte followed by zeros,
and remove everything from the last `0x80` byte onwards when decoding.
If you add padding to a field with existing data, `c:decode/1` must
also handle values written without padding.

## Limitations

Each value is encrypted with a random nonce, so encrypting the same
value twice gives different results. This means you can't query
encrypted fields: `where: u.ssn == ^ssn` will never match. If you need
to look up encrypted values, store a hash of them in a separate
column using `Ecto.HMAC`.

Encrypted values are stored as raw binaries, so they can't be
stored in fields of embedded schemas that are saved as JSON.

## Using outside of Ecto

`use Ecto.Encrypted` also defines `encrypt/1` and `decrypt/1` in
your module, which encrypt and decrypt binaries using its keys.
These functions skip `c:encode/1` and `c:decode/1`.

# `key`

```elixir
@type key() :: %{
  :tag =&gt; binary(),
  :cipher =&gt; atom(),
  :key =&gt; binary(),
  optional(atom()) =&gt; term()
}
```

A tag, an AEAD cipher supported by `:crypto`, and a key

# `decode`

```elixir
@callback decode(binary()) :: {:ok, term()} | :error
```

Decodes a decrypted binary back into a value.

Defaults to returning the binary as is.

# `encode`

```elixir
@callback encode(term()) :: {:ok, binary()} | :error
```

Encodes a value into a binary to be encrypted.

Defaults to accepting only binaries.

# `keys`

```elixir
@callback keys() :: [key(), ...]
```

Returns the list of keys.

The first key is used for encryption and all keys can be used for
decryption.

# `decrypt`

```elixir
@spec decrypt([key(), ...], binary()) :: {:ok, binary()} | :error
```

Decrypts `binary` using the key whose tag matches the one in `binary`.

Returns `:error` if no key matches the tag or if the data has been
tampered with. Raises `ArgumentError` if the matching key is invalid.

# `encrypt`

```elixir
@spec encrypt([key(), ...], binary()) :: binary()
```

Encrypts `plaintext` using the first key in `keys`.

The value key is derived by computing `HMAC-SHA256(key, "Ecto.Encrypted" <> salt)`,
truncated to the cipher's key length, where `salt` is 12 random bytes.
The result has the format:

    <<1, byte_size(tag)::8, tag::binary, salt::binary-12, iv::binary,
      ciphertext::binary, auth_tag::binary-16>>

where `1` is the version of the format. The version, the tag, and its
size are authenticated as additional data.

Raises `ArgumentError` if the first key is invalid.

---

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