As the System.Random
class relies on a pseudorandom number generator, it should not be used for security-critical applications or for protecting sensitive data. In such context, the System.Cryptography.RandomNumberGenerator
class which relies on a cryptographically strong random number generator (RNG) should be used in place.
private int RandomIntFromRNG(int min, int max)
{
var randomGenerator = RandomNumberGenerator.Create();
// Generate four random bytes
byte[] four_bytes = new byte[4];
randomGenerator.GetBytes(four_bytes);
// Convert the bytes to a UInt32
UInt32 scale = BitConverter.ToUInt32(four_bytes, 0);
// And use that to pick a random number >= min and < max
return (int)(min + (max - min) * (scale / (uint.MaxValue + 1.0)));
}