How to fix: Math.random() Used for Security Tokens
Math.random() was found in a context suggesting security token generation (combined with hex encoding or token/id variable names). Math.random() is not cryptographically secure and must not be used for tokens, session IDs, or CSRF values.
Why it matters
Math.random() outputs are predictable given the RNG seed. An attacker who observes any output can reconstruct the seed and predict all past and future values, enabling them to forge tokens, guess session IDs, or predict CSRF values.
AI code generators frequently use Math.random().toString(36) or Math.floor(Math.random() * N) for generating IDs and tokens. This is correct for non-security use cases (e.g., animation seeds) but critically wrong for anything security-related.
How to fix it
- 1Use crypto.randomUUID() for UUIDs.
- 2Use crypto.randomBytes(32).toString('hex') for tokens.
- 3In browsers, use crypto.getRandomValues() instead of Math.random().
- 4Never use Math.random() for session IDs, CSRF tokens, password reset tokens, or API keys.
Code examples
Secure token generation
// Bad (AI-generated)
const token = Math.random().toString(36).slice(2);
// Good
import { randomBytes } from 'node:crypto';
const token = randomBytes(32).toString('hex'); // 256 bits of entropyReferences
Detected automatically by VulnRadar. The check id is vibe-weak-random, stable across every scan so you can filter or diff on it.
More ai code checks
- LowGeneric Error Messages Leak No Context
- MediumTODO/FIXME Security Note in Response
- Higheval() Usage in Page Scripts
- HighSSL Certificate Verification Disabled
- CriticalHardcoded Credential in Authentication Logic
- CriticalJWT 'none' Algorithm Accepted
- CriticalSQL String Concatenation Pattern Detected
- MediumStack Trace Exposed in Response
Questions
- How severe is Math.random() Used for Security Tokens?
- VulnRadar rates this high severity in the ai code category. The severity is fixed per check, not scored per site, so the same finding is the same severity on every scan.
- Does VulnRadar check for this automatically?
- Yes. It runs as part of every scan under the check id vibe-weak-random, which stays the same between runs so you can filter, diff, or gate CI on it.
- Which standards does Math.random() Used for Security Tokens map to?
- It maps to CWE-330. In the OWASP Top 10 it falls under A02:2021.
Missing a check?
The detection set is open. If you know a misconfiguration this does not catch, propose it: the issue template asks for the threat model, how to detect it, the false-positive risk, and a test fixture, which is the same thing a maintainer would have to work out anyway.