logo

Database

C Sharp Insecure Random Key Generation

Description

Identifies the usage of cryptographically weak random number generators for key generation in C# code. Using non-cryptographic random number generators for cryptographic purposes can lead to predictable keys, making the cryptographic operations vulnerable to attacks.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    Examines method calls in C# code to identify usage of insecure random number generation methods

    Flags code when insecure random methods (like System.Random) are used in a context where cryptographic keys are being generated

    Verifies if the random number generation is part of an expression that involves cryptographic operations

    Reports a vulnerability when insecure random methods are used instead of cryptographically secure alternatives

Vulnerable code example

using System;

public class InsecureRandomExample 
{
    public byte[] GenerateKey()
    {
        var rng = new Random();  // Vulnerable: Using System.Random instead of RNGCryptoServiceProvider
        byte[] key = new byte[16];...

✅ Secure code example

using System;
using System.Security.Cryptography;

public class SecureRandomExample 
{
    public byte[] GenerateKey()
    {
        using (var rng = RandomNumberGenerator.Create())  // Secure: Using cryptographic RNG...