using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApplication1 { using System; using System.Security.Cryptography; /// /// Represents a random number generator, a device that produces a sequence of numbers that meet cryptographic requirements for randomness. /// /// /// Seed values are meaningless because this class uses a cryptographic service provider internally rather than a pseudo-random sequence. /// public class CryptoRandom : Random, IDisposable { /// /// The internal random number generator. /// private readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); /// /// Returns a random number between 0.0 and 1.0. /// /// /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0. /// /// /// Uses a cryptographic service provider internally rather than a pseudo-random sequence. /// 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. return Convert.ToDouble(number) / Convert.ToDouble(ulong.MaxValue); } #region IDisposable Support 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 } }