Pseudorandom number generators (PRNGs) produce sequences that only approximate true randomness and are not suitable for security-sensitive contexts.
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.
As the Math.random() function relies on a weak pseudorandom number generator, this function should not be used for security-critical
applications or for protecting sensitive data. In such contexts, a cryptographically strong pseudorandom number generator (CSPRNG) should be used
instead.
This rule raises an issue only when code uses the pseudorandom generator in a security context, for example to generate tokens, passwords, session identifiers, or keys, or in a file that imports a cryptographic module.
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.
Using a non-cryptographic PRNG to generate keys or initialization vectors weakens the security of the cryptographic scheme, potentially making it trivially breakable.
Use a cryptographically secure pseudorandom number generator (CSPRNG) instead of a non-cryptographic PRNG.
function generatePassword(length) {
let password = '';
for (let i = 0; i < length; i++) {
password += Math.floor(Math.random() * 10); // Noncompliant
}
return password;
}
function generatePassword(length) {
const array = new Uint32Array(length);
crypto.getRandomValues(array);
let password = '';
for (let i = 0; i < length; i++) {
password += array[i] % 10;
}
return password;
}