Generate Stronger Random Numbers using C# and VB.NET

The RNGCryptoServiceProvider Class implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). Here’s how to generate random numbers using this class. Make sure you import the System.Security.Cryptography namespace before using this sample code

C#

static void GenerateRandomNumber()
{
byte[] byt = new byte[4];
RNGCryptoServiceProvider rngCrypto =
new RNGCryptoServiceProvider();
rngCrypto.GetBytes(byt);
int randomNumber = BitConverter.ToInt32(byt, 0);
Console.WriteLine(randomNumber);
}

VB.NET

Shared Sub GenerateRandomNumber()
Dim byt As Byte() = New Byte(4) {}
Dim rngCrypto As New RNGCryptoServiceProvider()
rngCrypto.GetBytes(byt)
Dim randomNumber As Integer = BitConverter.ToInt32(byt, 0)
Console.WriteLine(randomNumber)
End Sub

image






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.

1 comment:

Anonymous said...

hey i wanna know that can u explain the code in detail like why u chose byte[] array and all and why did u put 4 rather then any other no il be gratefull if u can tell me that