Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用System.Security.Cryptography生成随机int值_C#_Random_Cryptography - Fatal编程技术网

C# 如何使用System.Security.Cryptography生成随机int值

C# 如何使用System.Security.Cryptography生成随机int值,c#,random,cryptography,C#,Random,Cryptography,我想使用System.Security.Cryptography从0到26生成随机的int值我该怎么做?我知道可以使用system.random来实现这一点,但我想使用system.Security.Cryptography那么您应该使用类来实现这一目的。但是根据你发布的内容 从0到26,我认为您应该使用Random类 为了生成加密强随机数,您应该使用继承自RandomNumberGenerator类的类,并提供生成加密随机数的机制,而不是直接使用RandomNumberGenerator类 您

我想使用System.Security.Cryptography从0到26生成随机的int值我该怎么做?我知道可以使用system.random来实现这一点,但我想使用system.Security.Cryptography

那么您应该使用类来实现这一目的。但是根据你发布的内容 从0到26,我认为您应该使用
Random

为了生成加密强随机数,您应该使用继承自
RandomNumberGenerator
类的类,并提供生成加密随机数的机制,而不是直接使用
RandomNumberGenerator


您可以在链接的MSDN文档中看到一个示例。

您可以使用该示例从加密RNG生成随机整数。然而,我很难解释一个场景,在密码学之外,这样一个工具是有用的

RNGCryptoServiceProvider CprytoRNG = new RNGCryptoServiceProvider();

// Return a random integer between a min and max value.
int RandomIntFromRNG(int min, int max)
{
    // Generate four random bytes
    byte[] four_bytes = new byte[4];
    CprytoRNG.GetBytes(four_bytes);

    // Convert the bytes to a UInt32
    UInt32 scale = BitConverter.ToUInt32(four_bytes, 0);

    // And use that to pick a random number >= min and < max
    return (int)(min + (max - min) * (scale / (uint.MaxValue + 1.0)));
}
RNGCryptoServiceProvider CprytoRNG=new RNGCryptoServiceProvider();
//返回最小值和最大值之间的随机整数。
int randomint fromrng(int最小值,int最大值)
{
//生成四个随机字节
字节[]四个字节=新字节[4];
CprytoRNG.GetBytes(四个字节);
//将字节转换为UInt32
UInt32 scale=BitConverter.ToUInt32(四个字节,0);
//然后用它来选择一个随机数>=min和
@ArtjomB.,它正在使用一个提供程序类
RNGCryptoServiceProvider
。见编辑后的答案。但是,是的,这就像使用
Random
类一样简单。是的,示例是kicker,但您应该概括地描述它是如何完成的。Poster不应该使用Random(),因为他希望生成一个0到26的数字。范围不决定方法,使用决定方法。如果需要该范围内的高度随机值,则应使用System.Security.Cryptography。Anon Coward的回答是一个很好的例子。除了在
CprytoRNG
中输入错误(“crytpo”是我的惯犯)之外,首选的方法是使用
RandomNumberGenerator rng=RandomNumberGenerator.Create()
,而不是直接依赖RNGCryptoServiceProvider类型(除非您担心工厂已通过CryptoConfig重新导入到非CSPRNG)。RandomNumberGenerator.Create()存在于.NET Core上,但RNGCryptoServiceProvider类不存在。单元测试和发现的值0,9从未生成9,因为最终生成以下代码:
(int)Math.Round(min+(max-min)*(scale/(uint.MaxValue+1.0)),0,中点舍入。远离零)