Cryptographically Secure Random Data
suggest changeSystem.Random is a pseudo-random number generator, so it is not suitable when the values must be unpredictable. RNGCryptoServiceProvider fills a buffer from the operating system's cryptographic generator. On current .NET, RandomNumberGenerator is the replacement.
The following code samples demonstrate how to generate Cryptographically Secure byte arrays, strings and numbers.
Random Byte Array
public static byte[] GenerateRandomData(int length)
{
var rnd = new byte[length];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(rnd);
return rnd;
}
Random integer
public static int GenerateRandomInt(int minVal=0, int maxVal=100)
{
var rnd = new byte[4];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(rnd);
var i = BitConverter.ToUInt32(rnd, 0);
return (int)(i % (uint)(maxVal - minVal + 1)) + minVal;
}
Random String
public static string GenerateRandomString(int length, string allowableChars=null)
{
if (string.IsNullOrEmpty(allowableChars))
allowableChars = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Generate random data
var rnd = new byte[length];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(rnd);
// Generate the output string
var allowable = allowableChars.ToCharArray();
var l = allowable.Length;
var chars = new char[length];
for (var i = 0; i < length; i++)
chars[i] = allowable[rnd[i] % l];
return new string(chars);
}
Taking a remainder is slightly biased when the range does not divide the full width of the random value. Math.Abs on a signed 32-bit value also throws for int.MinValue, so the integer sample uses an unsigned value instead.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents