Insecure Randomness
Learn how to prevent insecure randomness vulnerabilities with real code examples and best practices. Protect your applications from predictable random number generation and security threats.
Tools recognizing this:
Opengrep Fortify Checkmarx SonarQube Snyk Semgrep CodeQL
What is Insecure Randomness and How Does it Work?
Insecure Randomness is a security vulnerability that occurs when applications use weak random number generators for security-critical operations. It happens when developers use predictable random number generation methods instead of cryptographically secure alternatives.
Using weak random number generators can lead to various security issues:
Predictable session IDs or tokens
Weak cryptographic keys
Guessable password reset codes
Vulnerable temporary file names
Exploitable game mechanics or gambling systems
This guide covers Insecure Randomness vulnerabilities, examples, prevention methods, and how to implement secure random number generation using real-world techniques.
One Simple Insecure Randomness Example
Consider this classic example of generating a session token:
An attacker could predict the next token because:
Math.random()
uses a weak pseudo-random number generator
The resulting tokens would be:
Using Math.random(): Predictable sequence based on seed
This allows attackers to potentially guess valid session tokens and hijack user sessions.
Insecure Randomness Prevention Methods: How to Fix Your Code
The most efficient way to fix an Insecure Randomness issue in your code is using cryptographically secure random number generators.
Secure random number generators use entropy from the system to generate unpredictable values, making them suitable for security-critical operations. They ensure that generated values cannot be predicted even if an attacker knows previous values.
Code Samples
Vulnerable Code
Fixed Code
Fix Explanation
The vulnerable code uses java.util.Random which is not cryptographically secure.The fix uses SecureRandom which provides cryptographically strong random numbers.SecureRandom uses the operating system's entropy pool for better randomness.The generated values are suitable for security-sensitive operations.
Need more help in preventing Insecure Randomness?
Mobb supports fixing many forms of Insecure Randomness vulnerabilities, and can mitigate your issues in batch.
Start now for free at app.mobb.ai
We’d love your feedback!
We’re excited to hear your thoughts and ideas about fixing vulnerabilities.
Book a meeting or Contact us if you have any corrections, questions or suggestions.
Last updated
Was this helpful?