我想使用 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/