RNGCryptoServiceProvider - Random Number Review

后端 未结 7 795
旧时难觅i
旧时难觅i 2020-12-05 17:48

While looking for best attempts at generating truly random numbers, I stumbled upon this code example.

Looking for opinions on this snippet.

<
相关标签:
7条回答
  • 2020-12-05 18:35

    Don't use your code. Your solution is wrong and generates poor random numbers. I suggest my solution, which generates cryptographically strong random numbers:

    public class SecureRandom : RandomNumberGenerator
    {
        private readonly RandomNumberGenerator rng = new RNGCryptoServiceProvider();
    
    
        public int Next()
        {
            var data = new byte[sizeof(int)];
            rng.GetBytes(data);
            return BitConverter.ToInt32(data, 0) & (int.MaxValue - 1);
        }
    
        public int Next(int maxValue)
        {
            return Next(0, maxValue);
        }
    
        public int Next(int minValue, int maxValue)
        {
            if (minValue > maxValue)
            {
                throw new ArgumentOutOfRangeException();
            }
            return (int)Math.Floor((minValue + ((double)maxValue - minValue) * NextDouble()));
        }
    
        public double NextDouble()
        {
            var data = new byte[sizeof(uint)];
            rng.GetBytes(data);
            var randUint = BitConverter.ToUInt32(data, 0);
            return randUint / (uint.MaxValue + 1.0);
        }
    
        public override void GetBytes(byte[] data)
        {
            rng.GetBytes(data);
        }
    
        public override void GetNonZeroBytes(byte[] data)
        {
            rng.GetNonZeroBytes(data);
        }
    }
    
    0 讨论(0)
提交回复
热议问题