Strongbox

Strongbox — Encrypted fields for Ecto

Hex Version HexDocs CI Status

Encrypted fields for Ecto: values bound to their field, blind indexes to find them, and keys you can rotate.

A national ID, a phone number, a token for another service, notes about someone's health. Strongbox encrypts them in your app, before they reach the database, so a leaked backup, a read replica or a query run by hand shows only ciphertext. Your app reads them as it always did.

Early release. Before 1.0, a minor version may change the API.

Install

You need Elixir 1.17+ and Ecto 3.10+.

{:strongbox, "~> 0.1"}

On Elixir 1.17, add {:jason, "~> 1.4"} too, for encrypted maps and lists. 1.18 and later have their own JSON.

Your first encrypted field

Make a key, and keep it out of the code:

$ mix strongbox.gen.key
lF1n2s0x…=
# config/runtime.exs
config :my_app, :strongbox_key_k1, Strongbox.Key.decode!(System.fetch_env!("STRONGBOX_KEY_K1"))

A vault holds the keys:

defmodule MyApp.Vault do
  use Strongbox

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

Encrypt a field. Its column is :binary:

defmodule MyApp.Patient do
  use Ecto.Schema
  use Strongbox.Schema, vault: MyApp.Vault

  schema "patients" do
    field :name, :string
    encrypted_field :national_id
    encrypted_field :born_on, as: :date
    encrypted_field :notes, as: :map
  end
end
# the migration
add :national_id, :binary
add :born_on, :binary
add :notes, :binary

That's all: the fields are encrypted when saved and decrypted when loaded, and never show when a struct is inspected.

Finding a value again

Encrypted values can't be queried: the same value never encrypts twice the same way. Keep a blind index beside the field, a keyed hash you can look up:

# the vault
@impl true
def index_keys do
  [%{tag: "i1", key: Application.fetch_env!(:my_app, :strongbox_index_key_i1)}]
end

# the schema
encrypted_field :email, as: :string
blind_index :email_index, of: :email, normalize: [:trim, :downcase]

# the changeset
|> cast(attrs, [:email])
|> Strongbox.Changeset.put_indexes()
|> unique_constraint(:email_index)
Patient
|> Strongbox.Query.where_index(:email_index, "Ana@Example.com")
|> Repo.one()

The blind indexes guide has short indexes that tell less, slow ones for values with few possibilities, and what an index gives away.

What you get

Guides

License

MIT. See LICENSE.