View Source Cheatsheet
setup
Setup
define-a-vault-module
Define a vault module
This is the module you will use to encrypt/decrypt your ciphertext. You can have more than one!
defmodule MyApp.MyVault do
use Cloak.Vault, otp_app: :my_app
end
generate-an-encryption-key
Generate an encryption key
This will generate a 256-bit key in Base64 encoding that you can store in an environment variable.
32
|> :crypto.strong_rand_bytes()
|> Base.encode64
custom-cipher-module
Custom Cipher Module
If you don't want to use any of the included cipher modules, you can define your own. See Cloak.Cipher
.
defmodule MyApp.MyCipher do
@behaviour Cloak.Cipher
@impl true
def encrypt(plaintext, opts) do
# your logic here
end
@impl true
def decrypt(ciphertext, opts) do
# your logic here
end
@impl true
def can_decrypt?(ciphertext, opts) do
# return a boolean
end
end
configure
Configure
using-config
Using Config
This is the easiest option, and the vault will automatically read this configuration.
# config/runtime.exs
config :my_app, MyApp.MyVault,
ciphers: [
default: Cloak.Ciphers.AES.GCM,
tag: "AES.GCM.V1",
key: Base.decode64!("your-key-here"),
iv_length: 12
]
inside-the-vault-module
Inside the Vault module
This is best if you need to fetch the key from some custom store before you use it. Add these lines to your vault module.
defmodule MyApp.Vault do
use Cloak.Vault, otp_app: :my_app
@impl GenServer
def init(config) do
config =
Keyword.put(config, :ciphers, [
default: {
Cloak.Ciphers.AES.GCM,
tag: "AES.GCM.V1",
key: decode_env!("CLOAK_KEY"),
iv_length: 12
}
])
{:ok, config}
end
defp decode_env!(var) do
var
|> System.get_env()
|> Base.decode64!()
end
end
usage
Usage
encrypt
Encrypt
Safe: return any errors
MyApp.MyVault.encrypt("plaintext")
# => {:ok, "ciphertext"}
Unsafe: raise any errors
MyApp.MyVault.encrypt!("plaintext")
# => "ciphertext"
decrypt
Decrypt
Safe: return any errors
MyApp.MyVault.decrypt("ciphertext")
# => {:ok, "plaintext"}
Unsafe: raise any errors
MyApp.MyVault.decrypt!("ciphertext")
# => "plaintext"
usage-with-ecto
Usage with Ecto
See the cloak_ecto
library! Here's a preview:
defmodule MyApp.MySchema do
use Ecto.Schema
schema "table" do
field :encrypted_field, MyApp.Encrypted.Binary
end
end