logo

Database

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.

Weakness:

169 - Insecure service configuration - Keys

Category: Functionality Abuse

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)...