Tuesday, June 21, 2022

C# Random stories

There will be many scenarios we have to generate random numbers, ids or strings as a developer¹. If we ever played a game we know how important is to generate random things. In the .Net world, we will normally use Guid ² struct to generate random ids. To get random numbers, we use the Random class.

But there are more mechanisms in .Net to generate random things. That's what we are going to look in this post.

The problem with Random class in .Net

 The Random class has a lot of use cases and well documented with samples. Before we explore let us understand what is the issue with the famous class Random? 


The best place to understand is the "Remarks" section in the docs. The repetition happens when we initialize the Random class with same seed. 

RNGCryptoServiceProvider

What is "cryptographically secure random number" mentioned above? It can be an encryption key randomly generated to encrypt sensitive data. We all understand if the encryption key is guessable there is no value.
From the documentation, we will be redirected to the RNGCryptoServiceProvider⁴ class for generating something random useful for cryptographic use cases. This class generate a random data as byte[] array. But that can be converted to base64 in case our requirement is a random string.

But there is a catch. This class was is in use but now Obsolete⁵ and replaced with RandomNumberGenerator⁶ class.
So it is not a good path to take.

RandomNumberGenerator

This is an abstract base class so in order to create object we have to call its static Create(). Below goes the code to generate.


The code inside the extension methods goes below.

The above sample generate random bytes and convert to Base64 for display purpose. We can generate integer as well using the same byte array generation technique but with byte array to integer conversion.

Though it employs cryptographic methods, it is not full proof. It is again prone to prediction. If we really need unpredictable randomness we should look at external services such as random.org⁷ that uses atmospheric noise to generate randomness.

The sample I used are available in the GitHub repo.

References

No comments: