The .NET Framework includes the System.Random class, whose job it is to generate random numbers. It does so using a sequence based on a seed value, which is based on the system time by default. There are numerous possible seeds and predicting the exact time that a Random object will be created is not easy. That, coupled with the fact that the distribution of numbers generated by the sequence satisfies various statistical requirements for randomness, means that the Random class is quite suitable for most of your random number needs.
The main issue with the Random class is that, given a particular seed, the sequence will always produce the same numbers. That can actually be good for some testing scenarios but it does mean that the results could be manipulated. Where very high levels of unpredictability are required, the Random class is not suitable.
I've seen a number of people use various methods to generate more random random numbers. That's not really necessary though. The .NET Framework also includes the System.Security.Cryptography.RNGCryptoServiceProvider class for generating random numbers. It's output is sufficiently random for use in cryptography, so there's really no need for anything more random than that.
One issue with the RNGCryptoServiceProvider class, though, is that it populates byte arrays with random values. That's not always completely convenient though, as the most common need in applications is a random int value within a specific range. The Random class is nice and easy to use in that scenario, thanks to its Next method. What if we could combine the ease of use of the Random class with the increased randomness of the RNGCryptoServiceProvider class?
As it happens, we can. The Random class has a protected method named Sample that generates a double values in the range 0.0 <= x < 1.0. The result of that method is then used in the other methods to generate int values in a range. We can define our own class that inherits Random and overrides that Sample method to use RNGCryptoServiceProvider internally. Here's one I prepared earlier:
csharp Code:
using System;
using System.Security.Cryptography;
/// <summary>
/// Represents a random number generator, a device that produces a sequence of numbers that meet cryptographic requirements for randomness.
/// </summary>
/// <remarks>
/// Seed values are meaningless because this class uses a cryptographic service provider internally rather than a pseudo-random sequence.
/// </remarks>
public class CryptoRandom : Random, IDisposable
{
/// <summary>
/// The internal random number generator.
/// </summary>
private readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
/// <summary>
/// Returns a random number between 0.0 and 1.0.
/// </summary>
/// <returns>
/// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
/// </returns>
/// <remarks>
/// Uses a cryptographic service provider internally rather than a pseudo-random sequence.
/// </remarks>
protected override double Sample()
{
var data = new byte[8];
ulong number;
do
{
// Get 8 random bytes.
rng.GetBytes(data);
// Convert the bytes to an unsigned 64-bit number.
number = BitConverter.ToUInt64(data, 0);
}
while (number == ulong.MaxValue); // The result must be less than 1.0
// Divide the number by the largest possible unsigned 64-bit number to get a value in the range 0.0 <= N < 1.0.
private bool disposedValue; // To detect redundant calls
// IDisposable
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
// Dispose the underlying cryptographic random number generator.
rng.Dispose();
}
}
this.disposedValue = true;
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
You can create an instance of that class and use it in pretty much exactly the same way as you would a Random object. The only difference is that you will need to call its Dispose method when you're done, in order to dispose the internal RNGCryptoServiceProvider object. Sample usage:
csharp Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private readonly CryptoRandom rng = new CryptoRandom();
Last edited by jmcilhinney; Oct 30th, 2015 at 03:30 AM.
Reason: Fixed bug in Sample method that caused integer division instead of floating point division.