PRNGs are algorithms that produce sequences of numbers that only approximate true randomness. While they are suitable for applications like
simulations or modeling, they are not appropriate for security-sensitive contexts because their outputs can be predictable if the internal state is
known.
In contrast, cryptographically secure pseudorandom number generators (CSPRNGs) are designed to be secure against prediction attacks. CSPRNGs use
cryptographic algorithms to ensure that the generated sequences are not only random but also unpredictable, even if part of the sequence or the
internal state becomes known. This unpredictability is crucial for security-related tasks such as generating encryption keys, tokens, or any other
values that must remain confidential and resistant to guessing attacks.
For example, the use of non-cryptographic PRNGs has led to vulnerabilities such as:
When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that
will be generated, and use this guess to impersonate another user or access sensitive information. Therefore, it is critical to use CSPRNGs in any
security-sensitive application to ensure the robustness and security of the system.
As the java.util.Random
class relies on a non-cryptographic pseudorandom number generator, this class and relating
java.lang.Math.random()
method should not be used for security-critical applications or for protecting sensitive data. In such context,
the java.security.SecureRandom
class which relies on a CSPRNG should be used in place.
Ask Yourself Whether
- the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such
as a password, is hashed.
- the function you use is a non-cryptographic PRNG.
- the generated value is used multiple times.
- an attacker can access the generated value.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
- Use a cryptographically secure pseudo random number generator (CSPRNG) like "java.security.SecureRandom" in place of a non-cryptographic PRNG.
- Use the generated random values only once.
- You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.
Sensitive Code Example
Random random = new Random(); // Sensitive use of Random
byte bytes[] = new byte[20];
random.nextBytes(bytes); // Check if bytes is used for hashing, encryption, etc...
Compliant Solution
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
See