Pseudorandom number generators (PRNGs) produce sequences that only approximate true randomness and are not suitable for security-sensitive contexts.

Why is this an issue?

When software generates predictable values in a context requiring unpredictability, an attacker who knows or can guess the internal state of the PRNG may predict the next value that will be generated. The rule flags the use of non-cryptographic PRNGs in contexts where a cryptographically secure pseudorandom number generator (CSPRNG) is required, such as generating encryption keys, tokens, or other secret values.

What is the potential impact?

Predictable values

If an attacker can predict the values generated by a PRNG, they may be able to guess session tokens, encryption keys, password reset links, or other secrets, leading to unauthorized access or impersonation.

Broken cryptography

Using a non-cryptographic PRNG to generate keys or initialization vectors weakens the security of the cryptographic scheme, potentially making it trivially breakable.

How to fix it

Code examples

Use a cryptographically secure pseudorandom number generator (CSPRNG) instead of a non-cryptographic PRNG.

Noncompliant code example

import random

random.getrandbits(1) # Noncompliant
random.randint(0,9) # Noncompliant
random.random()  # Noncompliant

# These functions are sometimes used to generate salts by selecting characters from a string:
random.sample(['a', 'b'], 1)  # Noncompliant
random.choice(['a', 'b'])  # Noncompliant
random.choices(['a', 'b'])  # Noncompliant

Compliant solution

import secrets
import random

secrets.randbits(1)
secrets.randbelow(10)
secrets.token_hex(16)

random.SystemRandom().sample(['a', 'b'], 1)
secrets.choice(['a', 'b'])
random.SystemRandom().choices(['a', 'b'])

Resources

Documentation

Standards