Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities:
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.
As the System.Random
class relies on a pseudorandom number generator, it should not be used for security-critical applications or for
protecting sensitive data. In such context, the System.Cryptography.RandomNumberGenerator
class which relies on a cryptographically
strong random number generator (RNG) 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 generates a value which can be predicted (pseudo-random).
- 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
- Only use random number generators which are recommended by
OWASP or any other trusted organization.
- 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
var random = new Random(); // Sensitive use of Random
byte[] data = new byte[16];
random.NextBytes(data);
return BitConverter.ToString(data); // Check if this value is used for hashing or encryption
Compliant Solution
using System.Security.Cryptography;
...
var randomGenerator = RandomNumberGenerator.Create(); // Compliant for security-sensitive use cases
byte[] data = new byte[16];
randomGenerator.GetBytes(data);
return BitConverter.ToString(data);
See