Advertisement
debughf

Secure Random Class

Feb 13th, 2016
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1. using System;
  2. using System.Security.Cryptography;
  3. public class SecureRandom : RandomNumberGenerator
  4. {
  5.     private readonly RandomNumberGenerator rng = new RNGCryptoServiceProvider();
  6.     public int Next()
  7.     {
  8.         var data = new byte[sizeof(int)];
  9.         rng.GetBytes(data);
  10.         return BitConverter.ToInt32(data, 0) & (int.MaxValue - 1);
  11.     }
  12.     public int Next(int maxValue)
  13.     {
  14.         return Next(0, maxValue);
  15.     }
  16.     public int Next(int minValue, int maxValue)
  17.     {
  18.         if (minValue > maxValue)
  19.         {
  20.             throw new ArgumentOutOfRangeException();
  21.         }
  22.         return (int)Math.Floor((minValue + ((double)maxValue - minValue) * NextDouble()));
  23.     }
  24.     public double NextDouble()
  25.     {
  26.         var data = new byte[sizeof(uint)];
  27.         rng.GetBytes(data);
  28.         var randUint = BitConverter.ToUInt32(data, 0);
  29.         return randUint / (uint.MaxValue + 1.0);
  30.     }
  31.     public double NextDouble(double minimum, double maximum)
  32.     {
  33.         return NextDouble() * (maximum - minimum) + minimum;
  34.     }
  35.     public override void GetBytes(byte[] data)
  36.     {
  37.         rng.GetBytes(data);
  38.     }
  39.     public override void GetNonZeroBytes(byte[] data)
  40.     {
  41.         rng.GetNonZeroBytes(data);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement