Skip to content

Instantly share code, notes, and snippets.

@Toyz
Last active August 29, 2015 14:22
Show Gist options
  • Save Toyz/16921c25258d557d242b to your computer and use it in GitHub Desktop.
Save Toyz/16921c25258d557d242b to your computer and use it in GitHub Desktop.
using System;
using System.Security.Cryptography;
///<summary>
/// Represents a pseudo-random number generator, a device that produces random data.
///</summary>
classCryptoRandom : RandomNumberGenerator
{
privatestaticRandomNumberGenerator r;
///<summary>
/// Creates an instance of the default implementation of a cryptographic random number generator that can be used to generate random data.
///</summary>
public CryptoRandom()
{
r = RandomNumberGenerator.Create();
}
///<summary>
/// Fills the elements of a specified array of bytes with random numbers.
///</summary>
///<param name=”buffer”>An array of bytes to contain random numbers.</param>
publicoverridevoid GetBytes(byte[] buffer)
{
r.GetBytes(buffer);
}
///<summary>
/// Returns a random number between 0.0 and 1.0.
///</summary>
publicdouble NextDouble()
{
byte[] b = newbyte[4];
r.GetBytes(b);
return (double)BitConverter.ToUInt32(b, 0) / UInt32.MaxValue;
}
///<summary>
/// Returns a random number within the specified range.
///</summary>
///<param name=”minValue”>The inclusive lower bound of the random number returned.</param>
///<param name=”maxValue”>The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param>
publicint Next(int minValue, int maxValue)
{
return (int)Math.Round(NextDouble() * (maxValue – minValue – 1)) + minValue;
}
///<summary>
/// Returns a nonnegative random number.
///</summary>
publicint Next()
{
return Next(0, Int32.MaxValue);
}
///<summary>
/// Returns a nonnegative random number less than the specified maximum
///</summary>
///<param name=”maxValue”>The inclusive upper bound of the random number returned. maxValue must be greater than or equal 0</param>
publicint Next(int maxValue)
{
return Next(0, maxValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment