Last active
September 15, 2021 20:56
-
-
Save mudssrali/c45d273a136eba02bf6b09114441562a to your computer and use it in GitHub Desktop.
Elixir implementation of encryption and decryption using erlang's :crypto.block_encrypt and :crypto.block_decrypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Crypto.AES do | |
@block_size 16 | |
@secret_key "" | |
def encrypt(text) do | |
secret_key_hash = make_hash(@secret_key, 16) | |
text = pad_pkcs7(text, @block_size) | |
encrypted_text = :crypto.block_encrypt(:aes_ecb, secret_key_hash, text) | |
Base.encode64(encrypted_text) | |
end | |
def decrypt(ciphertext) do | |
secret_key_hash = make_hash(@secret_key, 16) | |
{:ok, ciphertext} = Base.decode64(ciphertext) | |
decrypted_text = :crypto.block_decrypt(:aes_ecb, secret_key_hash, ciphertext) | |
unpad_pkcs7(decrypted_text) | |
end | |
defp pad_pkcs7(message, blocksize) do | |
pad = blocksize - rem(byte_size(message), blocksize) | |
message <> to_string(List.duplicate(pad, pad)) | |
end | |
defp unpad_pkcs7(data) do | |
<<pad>> = binary_part(data, byte_size(data), -1) | |
binary_part(data, 0, byte_size(data) - pad) | |
end | |
defp make_hash(text, length) do | |
:crypto.hash(:sha512, text) | |
|> Base.encode16 | |
|> String.downcase | |
|> String.slice(0, length) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment