CA5394: Do not use insecure randomness

Property Value
Rule ID CA5394
Title Do not use insecure randomness
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

One of the methods of System.Random is invoked.

Rule description

Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated.

How to fix violations

If you need an unpredictable value for security, use a cryptographically strong random number generator like System.Security.Cryptography.RandomNumberGenerator or System.Security.Cryptography.RNGCryptoServiceProvider.

When to suppress warnings

It's safe to suppress warnings from this rule if you're sure that the weak pseudo-random numbers aren't used in a security-sensitive manner.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA5394
// The code that's violating the rule is on this line.
#pragma warning restore CA5394

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA5394.severity = none

For more information, see How to suppress code analysis warnings.

Pseudo-code examples

Violation

using System;

class ExampleClass
{
    public void ExampleMethod(Random random)
    {
        var sensitiveVariable = random.Next();
    }
}

Solution

using System;
using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(int toExclusive)
    {
        var sensitiveVariable = RandomNumberGenerator.GetInt32(toExclusive);
    }
}