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

标签 c# random cryptography

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

最佳答案

您可以使用它从 Crypto 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)));
}

关于c# - 如何使用 System.Security.Cryptography 生成随机 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668748/

相关文章:

java - 二维整数数组,随机填充 1 和 0。我该如何做到总有办法从一个角落走到另一个角落?

java - AES-256 可以在 API 级别 26+ 的 Android 设备上工作吗?

java - 使用 Java 安全提供程序分离摘要和签名

c# - 如何分割在 foreach 循环中迭代的元素

c# - 实现派生类接口(interface)方法的抽象基类

c# - 无法在 azure 上使用框架 4.6.1 执行 dotnet core 站点

c# - 如何在列表框中加载所有已知的颜色?

java - 如何在 while 循环内无错误地随机?

random - 从上下文无关文法生成 n 个语句

c# - 自定义非对称密码算法