logo

Database

Python Predictable Iv Nonce Source

Description

This detector identifies cryptographic operations that use predictable initialization vectors (IVs) or nonces. Using predictable IVs/nonces in encryption schemes compromises security by allowing attackers to derive patterns or recover plaintext, violating the fundamental requirement for randomness in cryptographic operations.

Weakness:

395 - Insecure generation of random numbers - Static IV

Category: Functionality Abuse

Detection Strategy

    • The detector first checks if any cryptographic libraries are imported in the Python code

    • It identifies dangerous imported functions that can generate predictable values (such as hardcoded bytes, sequential counters, or deterministic generators)

    • The detector searches for method calls to encryption functions (like encrypt, cipher methods)

    • When an encryption method is found, it traces back to examine how the cipher object was constructed

    • A vulnerability is reported when the cipher construction uses predictable IV/nonce sources identified in step 2, indicating the encryption operation may be using non-random initialization values

Vulnerable code example

import time
from Crypto.Cipher import AES
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

def encrypt_data(key, data):
    nonce = str(time.time()).encode()  # VULNERABLE: predictable nonce from system time
    cipher = Cipher(algorithms.AES(key), modes.GCM(nonce))
    encryptor = cipher.encryptor()...

✅ Secure code example

import os
from Crypto.Cipher import AES
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

def encrypt_data(key, data):
    nonce = os.urandom(12)  # SAFE: cryptographically random nonce
    cipher = Cipher(algorithms.AES(key), modes.GCM(nonce))
    encryptor = cipher.encryptor()...