How to generate cryptographically strong random numbers in C#

You can create strong random number values with the System.Security.Cryptography.RandomNumberGenerator class. You use these random key or salt values when you want to store salted password hashes. A salted password hash is a hash created from a password and a so-called salt where salt is a random value. This guarantees that even if two users select the same password, the result stored in the back-end store looks different, because the random salt value is hashed with the password. You should store the salt value in a separate field together with the password, because you need it for password validation. The next code lines show how to use System.Security.Cryptography.RandomNumberGenerator class:

C# in Depth, 3rd EditionManaged Windows VPS Hosting


byte[] RandomValue = new byte[16];

RandomNumberGenerator RndGen = RandomNumberGenerator.Create();


ResultLabel.Text = Convert.ToBase64String(RandomValue);