问题描述
我必须在给定范围内为生成密码的程序生成一个统一的,安全的随机整数.现在我用这个:
I have to generate a uniform, secure random integer within a given range for a program that generates passwords. Right now I use this :
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)
此方法可安全用于加密目的吗?如果没有,我该怎么办?
Is this method safe to use for cryptographic purposes ? If not, how should I do it ?
推荐答案
您可以查看从 https://gist.github.com/1017834 ,这是Stephen Toub和Shawn Farkas的原始版本.在此类中,他们实现了一些随机生成器,这些生成器似乎在密码上是安全的.
You can have a look to CryptoRandom class taken from https://gist.github.com/1017834 which is the Original version by Stephen Toub and Shawn Farkas. In this class they implement several random generators that seem to be cryptographically secures.
我在项目中使用了以下版本进行随机int生成.
I have used the following version in my projects for random int generation.
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;
}
}
这篇关于如何在一定范围内生成密码安全的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!