Skip to content

Commit bfcd9ea

Browse files
committed
Prototype of base64 wrapped encrypted value.
1 parent e91ff86 commit bfcd9ea

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

lib/encrypted-base64.ex

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
defmodule Fields.EncryptedBase64 do
2+
@moduledoc """
3+
An Ecto Type for encrypted fields.
4+
See `Fields.AES` for details on encryption/decryption.
5+
6+
## Example
7+
8+
schema "users" do
9+
field :name, Fields.EncryptedBase64
10+
end
11+
"""
12+
use Ecto.Type
13+
alias Fields.AES
14+
require Logger
15+
16+
def type(),
17+
do: :string
18+
19+
def cast(value),
20+
do: {:ok, to_string(value)}
21+
22+
def dump(value),
23+
do:
24+
value
25+
|> then(fn
26+
# Input value is nil. Store as-is. It's the developer's job
27+
# to run validations if they don't want that.
28+
nil -> value
29+
# Value is any kind of binary. Encrypt, and base64 encode.
30+
<<>> <> _ -> value |> to_string |> AES.encrypt() |> Base.encode64(padding: true)
31+
end)
32+
|> then(& {:ok, &1})
33+
34+
def load(value),
35+
do:
36+
value
37+
|> then(fn
38+
# We got nil from the database... Just use that.
39+
nil -> value
40+
# We got any binary. Decode64 and decrypt.
41+
<<>> <> _ -> value |> Base.decode64!(padding: true) |> AES.decrypt()
42+
end)
43+
|> then(& {:ok, &1})
44+
45+
def embed_as(_),
46+
do: :dump
47+
48+
def equal?(term1, term2),
49+
do: term1 == term2
50+
end

0 commit comments

Comments
 (0)