This title is an adaption of the quote from George Orwell's book Animal Farm:
All animals are equal, but some are more equal than others
So what is this post all about? During a code review I noticed the following code to create a random number in C#:
This code will return an integer between -1 and 2147483647. There is nothing wrong with this code until you know the context where it is used. Using System.Random
is a performant easy way to get random values, but this implementation is not truly random. System.Random
uses a seed to generate values from. The same seed will produce the same order of values. And similar seeds will produce similar values. This could lead to vulnerabilities a bad actor can use.
So we need a better solution…
Luckily a cryptographic safe alternative is provided in the form of the RandomNumberGenerator
class:
In the example above a new byte array of length 16 is created that will contain 16 random bytes. You can convert this yourself to an integer but you can also use the GetInt32()
method instead: