logo

Insecure generation of random numbers - Static IV - Elixir


Need

Ensuring secure initialization vectors for cryptographic operations


Context

  1. Usage of Elixir (version 1.10 and above) for building scalable and fault-tolerant applications
  2. Usage of Plug and Cowboy for HTTP request and response handling
  3. Usage of Ecto for data persistence
  4. Usage of crypto for cryptographic operations

Description

Insecure Code Example

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.

Steps

  1. Use :crypto.strong_rand_bytes to generate a random initialization vector for each encryption.
  2. Avoid using static, hardcoded initialization vectors.

Secure Code Example

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.


References

  • 395 - Insecure generation of random numbers - Static IV

  • Last updated

    2023/09/18