Hal*_*ked 1 c# random cryptography rngcryptoserviceprovider
我在google上搜索RNGCryptoServiceProvider,其中包含如何限制Max和Min之间范围的示例,并且仍能获得均匀分布.在我使用模运算符之前,但有时我得到奇怪的值(高于Max)...无论如何这个代码(信用到未知)种子随机使用来自RNGCCryptoServiceProvider的新种子,每次调用该方法.你们有什么感想?
public static int GetRandom(int min, int max)
{
byte[] b = new byte[sizeof(int)];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
int i = BitConverter.ToInt32(b, 0);
Random r = new Random(i);
return r.Next(min, max);
}
Run Code Online (Sandbox Code Playgroud)
使用加密类随机生成器为常规随机生成器播种没有意义.(根据最薄弱环节的原则......)只需使用随机生成器的单个实例,并重用它:
private static Random rnd = new Random();
public static int GetRandom(int min, int max) {
return rnd.Next(min, max);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1984 次 |
最近记录: |