Insecure generation of random numbers - Static IV - Elixir

Insecure generation of random numbers - Static IV - Elixir

Need

Ensuring secure initialization vectors for cryptographic operations

Context

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

Description

Non compliant code

        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

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

Compliant code

        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