Ensuring secure initialization vectors for cryptographic operations
defmodule MyApp.Crypto do
@iv "0123456789abcdef"
def encrypt(data, key) do
:crypto.block_encrypt(:aes_cbc128, key, @iv, data)
end
end
In this insecure code, a static, hardcoded initialization vector (IV) is used in the AES encryption. Using a static IV for multiple encryptions with the same key allows an attacker to analyze the patterns and potentially reverse-engineer the key.
defmodule MyApp.Crypto do
def encrypt(data, key) do
iv = :crypto.strong_rand_bytes(16)
{:iv, :crypto.block_encrypt(:aes_cbc128, key, iv, data)}
end
end
In the secure version, a new random initialization vector (IV) is generated for each encryption using :crypto.strong_rand_bytes. This method provides sufficient randomness and high entropy, which makes it very difficult for an attacker to predict the IVs.