Skip to content

Commit 5e709b6

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

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

lib/encrypted-base64.ex

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
alias Fields.AES
13+
use Ecto.Type
14+
def type, do: :binary
15+
16+
def cast(value),
17+
do: {:ok, to_string(value)}
18+
19+
def dump(value),
20+
do:
21+
value
22+
|> then(fn
23+
# Input value is nil. Store as-is. It's the developer's job
24+
# to run validations if they don't want that.
25+
nil -> value
26+
# Value is any kind of binary. Encrypt, and base64 encode.
27+
<<>> <> _ -> value |> to_string |> AES.encrypt() |> Base.encode64()
28+
end)
29+
|> then(& {:ok, &1})
30+
31+
def load(value),
32+
do:
33+
value
34+
|> then(fn
35+
# We got nil from the database... Just use that.
36+
nil -> value
37+
# We got any binary. Decode64 and decrypt.
38+
<<>> <> _ -> value |> Base.decode64!() |> AES.decrypt()
39+
end)
40+
|> then(& {:ok, &1})
41+
42+
def embed_as(_),
43+
do: :self
44+
45+
def equal?(term1, term2),
46+
do: term1 == term2
47+
end

0 commit comments

Comments
 (0)