RNGCryptoServiceProvider - 随机数回顾随机数、RNGCryptoServiceProvider

2023-09-02 20:47:29 作者:九理米的雾

在寻找最佳的尝试产生真正的随机数,我偶然发现了这个code的例子。

寻找对这个片段的意见。

Looking for opinions on this snippet.

using System;
using System.Security.Cryptography;

private static int NextInt(int min, int max)
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] buffer = new byte[4];

    rng.GetBytes(buffer);
    int result = BitConverter.ToInt32(buffer, 0);

    return new Random(result).Next(min, max);
}

来源:http://www.vcskicks.com/$c$c-snippet/rng-int.php

这将是pferred在使用滴答计数的种子,如$ P $:

Would this be preferred over using a tick count seed such as:

Random rand = new Random(Environment.TickCount); 
rand.Next(min, max);

注意:

我不是找第三方随机数据提供商如 Random.org 的,因为这样的依赖关系是不现实的应用的

I am not looking for third party random data providers such as Random.org, as such a dependency is not realistic to the application.

推荐答案

那么,使用 RNGCryptoServiceProvider 给你一个难以猜测的密码强度的种子,而环境.TickCount 是,从理论上讲,predictable。

Well, using RNGCryptoServiceProvider gives you an unguessable crypto-strength seed whereas Environment.TickCount is, in theory, predictable.

在连续快速拨打您的 NextInt 方法多次在另一个重要的区别是显而易见的。使用 RNGCryptoServiceProvider 每一次都会种子随机对象使用不同的密码强度的数量,这意味着它会去上返回一个不同的随机数为每个呼叫。使用计时单位计数风险相同的号码,每次播种随机对象(如果该方法在同一打过几次电话嘀),这意味着它会继续返回相同的(假定是随机的)数为每个呼叫

Another crucial difference would be evident when calling your NextInt method several times in quick succession. Using RNGCryptoServiceProvider will seed the Random object with a different crypto-strength number each time, meaning that it will go on to return a different random number for each call. Using TickCount risks seeding the Random object with the same number each time (if the method is called several times during the same "tick"), meaning that it will go on to return the same (supposedly random) number for each call.

如果你真正需要的真正的随机数,那么你不应该使用计算机来生成这些都:你应该测量放射性衰变或类似的东西,真正的联合国predictable

If you genuinely need truly random numbers then you shouldn't be using a computer to generate them at all: you should be measuring radioactive decay or something similarly, genuinely unpredictable.