Insecure encryption algorithm - ECB - Elixir

Insecure encryption algorithm - ECB - Elixir

Need

Securely encrypt sensitive information.

Context

  • Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  • Usage of crypto module for encryption and decryption

Description

Non compliant code

        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.

Steps

  • Use a more secure encryption mode, such as Cipher Block Chaining (CBC) or Galois/Counter Mode (GCM).
  • Use an Initialization Vector (IV) for encryption, which should be unique for each encryption operation.

Compliant code

        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.

References