Home / Cryptography / Cryptographic Random Numbers

Cryptographic Random Numbers

Random numbers are essential in cryptography as you need them for generating encryption keys for symmetric algorithms such as AES, as well as for adding entropy into hashing functions and key derivation functions.

Usually in .NET, when you want to generate a random number or a pseudorandom number, you would make use the System.Random object to generate the number. For most situations, this is fine and certainly will provide the look of randomness when you apply a different seed each time. When you are dealing with security however, System.Random is not sufficient as the result of System.Random is very deterministic and predictable.

A better approach is to use the RNGCryptoServiceProvider object in the System.Cryptography namespace. RNGCryptoServiceProvider provides much better randomness than System.Random, but it does come at a slight cost as the call into RNGCryptoServiceProvider is much slower. However, this is a necessary trade-off if you require good quality, nondeterministic random numbers for key generation.

The following code demonstrates how to use RNGCryptoServiceProvider.

public static byte[] GenRandomNum(int length){

using (var rNumGen = new RNGCryptoServiceProvider())


var rNum = new byte[length];


return rNum;



Once you have constructed the RNGCryptoServiceProvider object, you make a call to GetBytes() by passing in a pre-instanced, fixed-length byte array. If, for example, you wanted to generate a random number to use as a 256-bit key for the AES encryption algorithm, you would create an array that was 32 bytes in length, as 32 bytes multiplied by 8 bits in a byte gives you 256 bits total.

Apart from speed of execution and the nondeterministic nature of RNGCryptoServiceProvider, the other difference between this and System.Random is that RNGCryptoServiceProvider is thread safe and System.Random is not.

for (int i = 0; i 10; i++)


Console.WriteLine(“Random Number ” + i + ” : ”

+ Convert.ToBase64String(Random.GenerateRandomNumber(32)));


In the sample code, we generate 10 sets of 32-byte random numbers by using the RNGCryptoServiceProvider and write the results to the console window. The GenerateRandomNumber method returns a byte array that is the same size as the parameter that you pass into the method. When we output the random number onto the screen, we first convert it to a Base64 string. This is common practice when displaying the results of a cryptographic operation on the screen. If you need to convert from a Base64 encoded string back into a byte array, you call Convert.FromBase64String.

Check Also

digital signature

Digital Signature

An essential purpose of cryptography would be  to ensure nonrepudiation of a delivered message. This …

Leave a Reply

Your email address will not be published. Required fields are marked *