Securely encrypt sensitive information.
defmodule MyApp.Crypto do
def encrypt(text, key) do
:crypto.block_encrypt(:aes_ecb, key, text)
end
def decrypt(ciphertext, key) do
:crypto.block_decrypt(:aes_ecb, key, ciphertext)
end
end
The code uses the Electronic Code Book (ECB) mode for AES encryption, which is not secure. In ECB mode, the same plaintext block will always produce the same ciphertext block, creating patterns that could be exploited.
defmodule MyApp.Crypto do
def encrypt(text, key, iv) do
:crypto.block_encrypt(:aes_cbc128, key, iv, text)
end
def decrypt(ciphertext, key, iv) do
:crypto.block_decrypt(:aes_cbc128, key, iv, ciphertext)
end
end
This secure Elixir code example uses the CBC mode for AES encryption, which is more secure than ECB mode. It also uses an Initialization Vector (IV) for encryption, which should be unique for each encryption operation.