Skip to content

Instantly share code, notes, and snippets.

@thiamsantos
Last active October 24, 2019 17:19
Show Gist options
  • Save thiamsantos/0c588d4e730748a1401693f55f647751 to your computer and use it in GitHub Desktop.
Save thiamsantos/0c588d4e730748a1401693f55f647751 to your computer and use it in GitHub Desktop.
defmodule Crypto do
def encrypt(data, key) when is_binary(data) and is_binary(key) do
iv = :crypto.strong_rand_bytes(16)
cipher = :crypto.block_encrypt(:aes_cbc256, hash_key(key), iv, pad(data))
Base.encode64("#{iv}#{cipher}")
end
def decrypt(digest, key) when is_binary(digest) and is_binary(key) do
text = Base.decode64!(digest)
iv = Kernel.binary_part(text, 0, 16)
cypher = Kernel.binary_part(text, 16, 16)
:aes_cbc256
|> :crypto.block_decrypt(hash_key(key), iv, cypher)
|> unpad()
end
defp hash_key(key) do
:crypto.hash(:sha256, key)
end
# pad data using PKCS#5
defp pad(msg) do
bytes_remaining = rem(byte_size(msg), 16)
padding_size = 16 - bytes_remaining
msg <> :binary.copy(<<padding_size>>, padding_size)
end
defp unpad(msg) do
padding_size = :binary.last(msg)
if padding_size <= 16 do
msg_size = byte_size(msg)
if binary_part(msg, msg_size, -padding_size) == :binary.copy(<<padding_size>>, padding_size) do
{:ok, binary_part(msg, 0, msg_size - padding_size)}
else
:error
end
else
:error
end
end
end
data = "yes"
key = "secret"
data
|> Crypto.encrypt(key)
|> IO.inspect()
|> Crypto.decrypt(key)
|> IO.inspect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment