Python Hardcoded Aes Key
Description
Detects hardcoded AES encryption keys in Python code. Using hardcoded encryption keys is a serious security risk as it can lead to compromise of encrypted data if the source code is exposed. Keys should be securely managed and retrieved from external configuration or key management systems.
Detection Strategy
• Check for calls to AES.new function from PyCrypto/PyCryptodome library
• Verify if the first argument (encryption key) passed to AES.new is a string literal
• Report a vulnerability if a hardcoded string is used as the encryption key
Vulnerable code example
from Crypto.Cipher import AES
def encrypt_data():
key = "SecretPassword123" # Vulnerable: Hardcoded encryption key
cipher = AES.new(key, AES.MODE_CFB, b'1234567890123456')
return cipher.encrypt(b"sensitive data")✅ Secure code example
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_data(data: bytes, key: bytes) -> tuple[bytes, bytes, bytes]:
# Generate random nonce for each encryption
nonce = get_random_bytes(16)
# Use EAX mode which provides authenticated encryption
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.