hashlib — improper prng
Improper Randomness for Cryptographic hashlib Functions
This rule detects the use of non-cryptographically secure randomness sources,
such as Python's random() function, as inputs to cryptographic functions
like hashlib.scrypt(). Using non-secure randomness sources can weaken the
cryptographic strength of functions that rely on unpredictability for security.
Cryptographic functions, including key generation, encryption, and hashing,
require a source of randomness that is unpredictable and secure against
attack. The standard random() function in Python is designed for statistical
modeling and simulations, not for security purposes, as it generates
predictable sequences that can be reproduced if the seed value is known.
Using random() for cryptographic purposes, such as generating salts or keys,
compromises security by making the output potentially predictable to attackers.
Ensure all cryptographic operations utilize a cryptographically secure source
of randomness. Python provides the secrets module for generating secure
random numbers suitable for security-sensitive applications, including key
generation and creating salts for hashing functions.
Example
| hashlib_improper_prng_scrypt.py | |
|---|---|
Example Output
> precli tests/unit/rules/python/stdlib/hashlib/examples/hashlib_improper_prng_scrypt.py
⚠️ Warning on line 7 in tests/unit/rules/python/stdlib/hashlib/examples/hashlib_improper_prng_scrypt.py
PY035: Use of Insufficiently Random Values
The 'random.randbytes' pseudo-random generator should not be used for security purposes.
Remediation
For security or cryptographic uses use a secure pseudo-random generator such
as os.urandom() or secrets.token_bytes().
| hashlib_improper_prng_scrypt.py | |
|---|---|
Default Configuration
See also
Info
New in version 0.4.3