Description
Math.random() provides no guarantee against prediction for session IDs, reset tokens, OTPs or CSRF tokens. A short code can also be easy to guess even when chosen at random.
Potential impact
Predictable values can expose accounts or sessions and undermine password resets, additional authentication or CSRF protection. Violating the requirements for keys, nonces or IVs can weaken confidentiality or integrity.
Remediation
- Use
window.crypto.getRandomValuesin browsers orcrypto.randomBytesin Node.js. For numeric codes in Node.js, usecrypto.randomInt. - Give random tokens sufficient entropy, for example at least 128 bits. For short OTPs, enforce expiry and attempt limits. For keys, nonces and IVs, follow the algorithm’s length, uniqueness and unpredictability requirements.
- Encode random bytes as hex or base64url. For a custom alphabet, use an unbiased mapping such as rejection sampling. Limit each token’s purpose, lifetime and permitted uses, and protect its storage and transmission.
Examples
Before
javascript
// BAD: Use Math.random() for a security-sensitive token
function createResetToken() {
// Predictable output with limited entropy
const token =
Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
return token; // Unsuitable for reset tokens, sessions or API keys
}
After
javascript
// GOOD (Node.js): CSPRNG for a 256-bit token
const crypto = require("crypto");
function createResetToken() {
return crypto.randomBytes(32).toString("hex"); // 64 hexadecimal characters, without encoding bias
}
// GOOD (Browser): Web Crypto API
function createCsrfToken() {
const bytes = crypto.getRandomValues(new Uint8Array(32)); // 256 bits
// Encode as base64url
let b64 = btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
return b64;
}
Run the two functions in their respective environments. The Node.js function encodes 32 bytes as 64 hexadecimal characters. The browser function encodes 32 bytes as base64url.