logo

Insecure Encryption Algorithm - Cipher Block Chaining - Elixir


Need

To ensure that data encryption and decryption processes are secure, minimizing the risk of data being compromised


Context

  1. Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications
  2. Usage of Elixir's :crypto module for cryptographic operations

Description

Insecure Code Example

defmodule InsecureCipher 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

This code snippet is using the :aes_cbc128 mode for the block cipher which is considered insecure due to vulnerabilities like the padding oracle attack. It makes it possible for an attacker to decrypt data without knowing the key.

Steps

  1. Switch from CBC mode to GCM mode.
  2. Make sure to use a secure source of random numbers for the IV (Initialization Vector).
  3. Always use secure and updated cryptographic libraries.

Secure Code Example

defmodule SecureCipher do
  def encrypt(data, key, iv, aad) do
    :crypto.crypto_one_time(:aes_gcm, key, iv, {aad, data}, :encrypt)
  end
  def decrypt(ciphertext_with_tag, key, iv, aad) do
    :crypto.crypto_one_time(:aes_gcm, key, iv, {aad, ciphertext_with_tag}, :decrypt)
  end
end

This secure code example uses the AES GCM mode for the block cipher which provides authenticated encryption. It also adds data integrity through the use of additional authenticated data (AAD). This makes it secure against attacks like the padding oracle attack.


References

  • 094 - Insecure Encryption Algorithm - Cipher Block Chaining

  • Last updated

    2023/09/18