logo

Database

C Sharp Insecure Random Key Generation

Description

This detector identifies insecure random number generation used for cryptographic key material in C# code. Using non-cryptographically secure random generators (e.g., `System.Random`) to produce keys, IVs, or seeds for cryptographic operations can lead to predictable values, making encrypted data vulnerable to brute-force or prediction attacks.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    • First, the detector checks whether the analyzed file imports any cryptography-related namespaces (e.g., System.Security.Cryptography or similar crypto libraries). If no such namespace is imported, the file is skipped entirely.

    • For each candidate expression in the file, the detector checks if it is a member access expression (e.g., accessing a property or method on an object) that resolves to a known insecure random sink — such as reading bytes or values from a non-cryptographic random source in a crypto context.

    • Alternatively, the detector checks if the expression is an object instantiation (constructor call) that creates an instance of an insecure random generator type (e.g., `new Random()`) in a context associated with cryptographic key generation.

    • A vulnerability is reported when either of the above sink patterns is found within a file that uses cryptographic namespaces, indicating that insecure randomness is being used where cryptographically strong randomness (e.g., RNGCryptoServiceProvider or RandomNumberGenerator) is required.

Vulnerable code example

using System;
using System.Security.Cryptography;

public class VulnerableExample
{
    public Aes WeakAesKey()
    {
        var rng = new Random();...

✅ Secure code example

using System;
using System.Security.Cryptography;

public class SecureExample
{
    public Aes SafeAesKey()
    {
        byte[] key = RandomNumberGenerator.GetBytes(32); // SAFE: CSPRNG replaces predictable System.Random...