我必须为生成密码的程序生成给定范围内的统一、安全的随机整数。现在我用这个:
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] rand = new byte[4];
rng.GetBytes(rand);
int i = BitConverter.ToUInt16(rand, 0);
int result = i%max; // max is the range's upper bound (the lower is 0)
此方法可安全用于加密目的吗?如果不是,我该怎么办?
您可以查看来自的 CryptoRandom 类niik/CryptoRandom.cs https://gist.github.com/1017834哪一个是original斯蒂芬·托布和肖恩·法卡斯的版本。在这个课程中,他们实现了几个似乎在密码学上安全的随机生成器。
我在我的项目中使用了以下版本来生成随机整数。
public class RandomGenerator
{
readonly RNGCryptoServiceProvider csp;
public RandomGenerator()
{
csp = new RNGCryptoServiceProvider();
}
public int Next(int minValue, int maxExclusiveValue)
{
if (minValue >= maxExclusiveValue)
throw new ArgumentOutOfRangeException("minValue must be lower than maxExclusiveValue");
long diff = (long)maxExclusiveValue - minValue;
long upperBound = uint.MaxValue / diff * diff;
uint ui;
do
{
ui = GetRandomUInt();
} while (ui >= upperBound);
return (int)(minValue + (ui % diff));
}
private uint GetRandomUInt()
{
var randomBytes = GenerateRandomBytes(sizeof(uint));
return BitConverter.ToUInt32(randomBytes, 0);
}
private byte[] GenerateRandomBytes(int bytesNumber)
{
byte[] buffer = new byte[bytesNumber];
csp.GetBytes(buffer);
return buffer;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)