Skip to main content

Insecure Encryption Algorithm - AES

Need

Secure encryption of sensitive data.

Context

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

Description

Non compliant code

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

  • Use a secure encryption mode like GCM which also provides data authenticity.
  • 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.

Compliant code

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