gpt4 book ai didi

c# - 如何生成一个范围内的加密安全随机整数?

转载 作者:太空狗 更新时间:2023-10-29 17:49:08 26 4
gpt4 key购买 nike

我必须为生成密码的程序生成一个给定范围内的统一、安全的随机整数。现在我用这个:

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)

此方法用于加密目的是否安全?如果没有,我应该怎么做?

最佳答案

您可以查看取自 niik/CryptoRandom.cs 的 CryptoRandom 类 这是 Stephen Toub 和 Shawn Farkas 的原始版本。在这个类中,他们实现了几个随机生成器,这些生成器似乎是加密安全的。

我在我的项目中使用了以下版本来生成随机整数。

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;
}
}

关于c# - 如何生成一个范围内的加密安全随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com