danielberkompas / cloak_ecto

Encrypted fields for Ecto
MIT License
195 stars 31 forks source link

Cloak.Ecto

Hex Version Hex Docs Total Download Last Updated Build Status Coverage Status

Easily encrypt fields in your Ecto schemas. Relies on Cloak for encryption.

Usage

Cloak.Ecto helps you create Ecto.Type modules which automatically encrypt and decrypt your data. You simply define a type and set the type of your fields, and Cloak.Ecto handles the rest.

defmodule MyApp.Encrypted.Binary do
  use Cloak.Ecto.Binary, vault: MyApp.Vault
end
defmodule MyApp.EctoSchema do
  use Ecto.Schema

  schema "table_name" do
    field :encrypted_field, MyApp.Encrypted.Binary

    # ...
  end
end

When Ecto writes the fields to the database, Cloak encrypts the values into a binary blob, using a configured encryption algorithm chosen by you.

iex> Repo.insert!(%MyApp.EctoSchema{encrypted_field: "plaintext"})
08:46:08.862 [debug] QUERY OK db=3.4ms
INSERT INTO "table_name" ("encrypted_field") 
VALUES ($1) RETURNING "id", "encrypted_field" [
  <<1,10, 65, 69, 83, 46, 67, 84, 82, 46, 86, 49, 
    69, 92, 173, 219, 203, 238, 26, 58, 236, 5, 
    104, 23, 12, 10, 182, 31, 221, 89, 22, 58, 
    34, 79, 109, 30, 70, 254, 56, 93, 102, 84>>
]

Likewise, when Ecto reads the encrypted blob out of the database, Cloak will automatically decrypt the value into the intended data type at runtime.

iex> Repo.get(MyApp.EctoSchema, 1)
%MyApp.EctoSchema{encrypted_field: "plaintext"}

For complete usage instructions, see the Hex documentation.

Troubleshooting

See our troubleshooting guide for solutions to common issues.

Notable Features

Security Notes

Use Without Ecto

If you want to use Cloak without Ecto, see cloak instead.

Local Development

To develop this library locally, you will need to install the correct version of Elixir and Postgres. The easiest way to set everything up is with Docker and docker-compose:

$ cd cloak_ecto
# Runs the bin/test script in the context of Docker
$ docker-compose run code bin/test
# To access a terminal with mix, use this command:
$ docker-compose run code bash
# Run any command of your choosing:
root@234098234oij:/app# mix docs