logo

Insecure Encryption Algorithm - AES - Elixir


Need

Secure encryption of sensitive data.


Context

  1. Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  2. Usage of crypto module for encryption

Description

Insecure Code Example

defmodule MyApp.Crypto 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

The code is vulnerable because it uses AES encryption in CBC mode, which is susceptible to padding oracle attacks. The encryption mode used does not ensure the authenticity of the data, which can lead to vulnerabilities.

Steps

  1. Use a secure encryption mode like GCM which also provides data authenticity.
  2. Replace the :aes_cbc128 atom with :aes_gcm in the :crypto.block_encrypt/3 and :crypto.block_decrypt/3 functions, and use an appropriate authentication tag.

Secure Code Example

defmodule MyApp.Crypto do
  def encrypt(data, key, iv, aad) do
    :crypto.block_encrypt(:aes_gcm, {key, iv}, aad, data)
  end

  def decrypt(ciphertext, key, iv, aad, tag) do
    :crypto.block_decrypt(:aes_gcm, {key, iv}, aad, tag, ciphertext)
  end
end

In this secure code example, AES encryption is used in GCM mode, which provides both data confidentiality and authenticity. This protects against padding oracle attacks and ensures that the encrypted data has not been tampered with.


References

  • 265 - Insecure Encryption Algorithm - AES

  • Last updated

    2023/09/18