Weak Random Number Generation High

Depending on the context, generating weak random numbers may expose cryptographic functions which rely on these numbers to be exploitable. When generating numbers for sensitive values such as tokens, nonces, and cryptographic keys, it is recommended that the RandomNumberGenerator class be used.

Detector ID
csharp/weak-random-number-generation@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1public void WeakRandomNumberGenerationNoncompliant()
2{
3    var randomnumber = new System.Random();
4    byte[] key = new byte[16];
5    randomnumber.NextBytes(key);
6    // Noncompliant: An insecure random number generator (RNG) is used to create cryptographic key.
7    var c = new AesGcm(key);
8}

Compliant example

1public void WeakRandomNumberGenerationCompliant()
2{
3    var randomnumber = System.Security.Cryptography.RandomNumberGenerator.Create();
4    byte[] key = new byte[16];
5    randomnumber.GetBytes(key);
6    // Compliant: Secure random number generator (RNG) is used to create cryptographic key.
7    var c = new AesGcm(key);
8}