How can I encrypt a field of an embedded schema using Cloak?

Hi there,

How can I encrypt a specific field of an embedded schema in Ecto using Cloak.Ecto?

I have something like this:

defmodule MyApp.MySchema do 
  schema "my_schema" do
    embeds_many :my_embed, MyApp.MyEmbed
  end
end

defmodule MyApp.MyEmbed do 
  embedded_schema do 
    field :some_field 
    field :some_encrypted_field, MyApp.Encrypted.Binary
  end
end

However some_encrypted_field is in plain text.
I have setup Cloak correctly for other records/fields, but couldn’t get it to work with embedded schemas.

Looks to me that it’s not possible as the underlying map would need to be stored in the db as JSON but cannot be encoded as JSON:

iex(5)> map
%{
  "field" => <<1, 10, 65, 69, 83, 46, 71, 67, 77, 46, 86, 49, 77, 106, 7, 215,
    34, 88, 207, 175, 58, 88, 70, 232, 78, 230, 137, 18, 84, 54, 118, 166, 72,
    41, 72, 159, 20, 41, 218, 93, 76, 160, 88, 148, 123>>
}
iex(6)> Jason.encode!(map)
** (Jason.EncodeError) invalid byte 0xD7 in <<1, 10, 65, 69, 83, 46, 71, 67, 77, 46, 86, 49, 77, 106, 7, 215, 34, 88, 207, 175, 58, 88, 70, 232, 78, 230, 137, 18, 84, 54, 118, 166, 72, 41, 72, 159, 20, 41, 218, 93, 76, 160, 88, 148, 123>>
    (jason 1.4.4) lib/jason.ex:164: Jason.encode!/2
    iex:6: (file)

It can’t be encoded as the jsonb Postgres type. The json type should work though.