Generate Random Numbers in .NET using RNGCryptoServiceProvider

I have written a couple of posts in the past about generating random numbers in .NET. Generating a random number is as simple as doing the following:

static void Main(string[] args)
{
// code from DevCurry.com
byte[] randomBytes = new byte[4];
Random rando = new Random();
rando.NextBytes(randomBytes);
foreach (byte byteValue in randomBytes)
Console.Write("{0, 4}", byteValue);

Console.ReadLine();
}

The Random class generates pseudo random numbers, based on a seed value. It uses the system clock to generate its seed value. However we were working on a security API and needed an algorithm with a more sophisticated seed value to generate cryptographically secure random numbers. Here’s how we did it using the RNGCryptoServiceProvider class:

static void Main(string[] args)
{
// code from DevCurry.com
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rngCrypto =
new RNGCryptoServiceProvider();

rngCrypto.GetBytes(randomBytes);
Int32 rngNum = BitConverter.ToInt32(randomBytes, 0);

Console.WriteLine(rngNum);

Console.ReadLine();
}

The RNGCryptoServiceProvider uses a combination of OS counters, processing info etc. to generate random numbers. Here the GetBytes() fills an array of bytes with a cryptographically strong sequence of random values.

OUTPUT (random)

1187354021

Note: You cannot run a foreach loop here as you did above, since foreach cannot operate on variables of the RNGCryptoServiceProvider as it does not expose GetEnumerator.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: