← back to index

S2245 — Pseudorandom number generators (PRNGs) should not be used in security contexts

Language: C#  |  Type: VULNERABILITY  |  Severity: Major

Tags: cwe, former-hotspot

Pseudorandom number generators (PRNGs) produce sequences that only approximate true randomness and are not suitable for security-sensitive contexts.

Why is this an issue?

When software generates predictable values in a context requiring unpredictability, an attacker who knows or can guess the internal state of the PRNG may predict the next value that will be generated. The rule flags the use of non-cryptographic PRNGs in contexts where a cryptographically secure pseudorandom number generator (CSPRNG) is required, such as generating encryption keys, tokens, or other secret values.

What is the potential impact?

Predictable values

If an attacker can predict the values generated by a PRNG, they may be able to guess session tokens, encryption keys, password reset links, or other secrets, leading to unauthorized access or impersonation.

Broken cryptography

Using a non-cryptographic PRNG to generate keys or initialization vectors weakens the security of the cryptographic scheme, potentially making it trivially breakable.

How to fix it

As the System.Random class relies on a non-cryptographic pseudorandom number generator, it should not be used for security-critical applications or for protecting sensitive data. In such contexts, the System.Security.Cryptography.RandomNumberGenerator class which relies on a CSPRNG should be used instead.

Code examples

Use a cryptographically secure pseudorandom number generator (CSPRNG) instead of a non-cryptographic PRNG.

Noncompliant code example

var random = new Random(); // Noncompliant
byte[] data = new byte[16];
random.NextBytes(data);
return BitConverter.ToString(data);

Compliant solution

using System.Security.Cryptography;
...
var randomGenerator = RandomNumberGenerator.Create();
byte[] data = new byte[16];
randomGenerator.GetBytes(data);
return BitConverter.ToString(data);

Resources

Documentation

Standards