How to search cloak AES encrypted format data in Elixir and Postgresql DB

How to search cloak AES encrypted format data in Elixir and Postgresql DB.

What do you mean by “search” exactly?

You cannot search encrypted data without decrypting it first.

The way we addressed it is by having two columns for the same piece of data: one is the encrypted value, the other one is a hash of the value:

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

defmodule SomeEntity do
  schema "some_table" do
    field :some_field, MyApp.Encrypted.Binary, redact: true
    field :some_field_hash, Cloak.Ecto.SHA256, redact: true
  end
end

and then rely on the fact that casting the field will hash it:

from(e in SomeEntity, where: e.some_field_hash == ^some_value) |> Repo.all()

The hash is computed in the app so the filtering can be done in the DB.

3 Likes

It will allow only probabilistic equality checks, not searching for data in encrypted fields.

Yes, but then you can double check the narrow set of results in-memory.

I want to search records where match field is in cloak encrypted format.