Secure encryption of sensitive data.
defmodule MyApp.Crypto do
def encrypt(data, key, iv) do
:crypto.block_encrypt(:aes_cbc128, {key, iv}, data)
end
def decrypt(ciphertext, key, iv) do
:crypto.block_decrypt(:aes_cbc128, {key, iv}, ciphertext)
end
end
The code is vulnerable because it uses AES encryption in CBC mode, which is susceptible to padding oracle attacks. The encryption mode used does not ensure the authenticity of the data, which can lead to vulnerabilities.
defmodule MyApp.Crypto do
def encrypt(data, key, iv, aad) do
:crypto.block_encrypt(:aes_gcm, {key, iv}, aad, data)
end
def decrypt(ciphertext, key, iv, aad, tag) do
:crypto.block_decrypt(:aes_gcm, {key, iv}, aad, tag, ciphertext)
end
end
In this secure code example, AES encryption is used in GCM mode, which provides both data confidentiality and authenticity. This protects against padding oracle attacks and ensures that the encrypted data has not been tampered with.