using System;
using System.Security.Cryptography;
///
/// Represents a pseudo-random number generator, a device that produces random data.
///
class CryptoRandom : RandomNumberGenerator
{
private static RandomNumberGenerator r;
///
/// Creates an instance of the default implementation of a cryptographic random number generator that can be used to generate random data.
///
public CryptoRandom()
{
r = RandomNumberGenerator.Create();
}
///
/// Fills the elements of a specified array of bytes with random numbers.
///
///An array of bytes to contain random numbers.
public override void GetBytes(byte[] buffer)
{
r.GetBytes(buffer);
}
///
/// Fills an array of bytes with a cryptographically strong random sequence of nonzero values.
///
/// The array to fill with cryptographically strong random nonzero bytes
public override void GetNonZeroBytes(byte[] data)
{
r.GetNonZeroBytes(data);
}
///
/// Returns a random number between 0.0 and 1.0.
///
public double NextDouble()
{
byte[] b = new byte[4];
r.GetBytes(b);
return (double)BitConverter.ToUInt32(b, 0) / UInt32.MaxValue;
}
///
/// Returns a random number within the specified range.
///
///The inclusive lower bound of the random number returned.
///The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.
public int Next(int minValue, int maxValue)
{
return (int)Math.Round(NextDouble() * (maxValue - minValue - 1)) + minValue;
}
///
/// Returns a nonnegative random number.
///
public int Next()
{
return Next(0, Int32.MaxValue);
}
///
/// Returns a nonnegative random number less than the specified maximum
///
///The inclusive upper bound of the random number returned. maxValue must be greater than or equal 0
public int Next(int maxValue)
{
return Next(0, maxValue);
}
}