Microsoft .NET Code Analysis: Random Is an Insecure Random Number Generator

Generating random numbers is very common in computer programming. There is a newer and more secure method for generating random numbers in .NET. It’s common to see many developers writing code to generate random numbers using the following example:

Random random = new Random();

// Generate a random integer between 0 and 100 (exclusive)
int result = random.Next(0, 100);

Using Random in the way described above is considered a cryptographically weak pseudo-random number generator, which could potentially allow an attacker to predict security-sensitive values. To address this concern, the .NET team now strongly recommends using the RandomNumberGenerator, as demonstrated in the code excerpt below, taken from the Spargine OSS:

[ThreadStatic]
private static readonly RandomNumberGenerator _randomNumberGenerator;

static RandomData()
{
    _randomNumberGenerator = RandomNumberGenerator.Create();
}

public static byte[] GenerateByteArray(double sizeInKb)
{
    var bytes = new Span<byte>(new byte[Convert.ToInt32(sizeInKb * 1024)]);

    lock (_lock)
    {
        _randomNumberGenerator.GetBytes(bytes);
    }

    return bytes.ToArray();
}

Here are the compelling reasons to refactor your code and adopt the RandomNumberGenerator:

  • Security: RandomNumberGenerator offers a robust and secure method for generating random numbers, making it suitable for cryptographic operations and security-critical applications. In contrast, the Random class is not intended for such high-security purposes.
  • Quality: The randomness produced by RandomNumberGenerator is of superior quality and is not susceptible to the predictability concerns that can arise when using the Random class.

When I setup the CA5394 code analysis in my .editorConfig it looks like this: dotnet_diagnostic.CA5394.severity = warning

Performance

As demonstrated by the benchmark test results below, adopting the RandomNumberGenerator substantially boosts performance, yielding performance improvements of over fourfold in .NET 8!

Summary

Upon reviewing the codebase I utilized for this article, I identified 42 instances where the RandomNumberGenerator should be implemented.

For further guidance and insights, I highly recommend obtaining a copy of my book, “Rock Your Code: Coding Standards for Microsoft .NET” available on Amazon.com. Additionally, to explore more performance tips for .NET, I encourage you to acquire the 3rd edition of “Rock Your Code: Code & App Performance for Microsoft .NET” also available on Amazon.com.

To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig. I update this file quarterly, so remember to keep yours up to date as well. I hope you will check out my OSS project Spargine by using this link: https://bit.ly/Spargine.

Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

One thought on “Microsoft .NET Code Analysis: Random Is an Insecure Random Number Generator

Leave a Reply