C#中是否允许加密随机生成器种子?
作者:互联网
似乎没有办法在C#中手动播种RNGCryptoServiceProvider.我可以在下面做一些简单的事情来获得可重复的randomBytes进行调试吗?
RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
byte[] randomBytes = new byte[20];
rngCsp.GetBytes(randomBytes);
MessageBox.Show(Convert.ToBase64String(randomBytes));
我知道我可以手动输入20个字节,但这是一个痛苦,因为我真的需要超过20个.另外,我知道我可以使用非加密随机数发生器,但最后,我将需要最好的随机生成.
顺便说一下,我猜有些CPU有真正的随机生成,其中种子在物理上是不可能的,但我不认为我的CPU具有这种能力.我想知道是否有人确切知道我可以用我的CPU来重置RNGCryptoServiceProvider环境并欺骗RNGCryptoServiceProvider使用先前的种子…我想我可以设置我的时钟并重置一些“用户日志位”某处…我知道这不切实际,但想知道是否有人在这方面取得过成功(尽管微软的目标可能是防止这种情况).
解决方法:
没有办法为RNGCryptoServiceProvider播种.为调试生成确定性值的一种解决方案是派生自己的类,该类从System.Security.Cryptography.RandomNumberGenerator(RNGCryptoServiceProvider的基类)实现:
class DeterministicRandomGenerator : System.Security.Cryptography.RandomNumberGenerator
{
Random r = new Random(0);
public override void GetBytes(byte[] data)
{
r.NextBytes(data);
}
public override void GetNonZeroBytes(byte[] data)
{
// simple implementation
for (int i = 0; i < data.Length; i++)
data[i] = (byte)r.Next(1, 256);
}
}
注意,该实现使用种子为0的标准Random实现,确保确定性结果.现在,您可以使用此类代替RNGCryptoServiceProvider进行调试:
RandomNumberGenerator rngCsp =
#if DEBUG
new DeterministicRandomGenerator(); // get deterministic values if debugging
#else
new RNGCryptoServiceProvider(); // otherwise, use CryptoRNG
#endif
byte[] randomBytes = new byte[20];
rngCsp.GetBytes(randomBytes);
MessageBox.Show(Convert.ToBase64String(randomBytes));
编辑添加
I wonder if anybody knows exactly what I could do with my CPU to reset the RNGCryptoServiceProvider environment and trick RNGCryptoServiceProvider into using a prior seed
在内部,RNGCryptoServiceProvider调用Win32 CryptGenRandom
函数以使用加密随机值(Source and additional information)填充缓冲区.它不基于单个种子. (虽然Win32 API允许调用者提供带有补充随机数据的种子,但.NET API不会公开此功能.此上下文中种子的目的是提供应用程序可以访问的附加熵,而不是强制确定性序列.)CryptGenRandom文档说明:
To form the seed for the random number generator, a calling application supplies bits it might have—for instance, mouse or keyboard timing input—that are then combined with both the stored seed and various system data and user data such as the process ID and thread ID, the system clock, the system time, the system counter, memory status, free disk clusters, the hashed user environment block. This result is used to seed the pseudorandom number generator (PRNG). In Windows Vista with Service Pack 1 (SP1) and later, an implementation of the AES counter-mode based PRNG specified in NIST Special Publication 800-90 is used. In Windows Vista, Windows Storage Server 2003, and Windows XP, the PRNG specified in Federal Information Processing Standard (FIPS) 186-2 is used.
结果是“重置”RNGCryptoServiceProvider以强制它重复前一个序列,这在设计上并不是一种实用的方法.
标签:c,random,visual-studio,prng 来源: https://codeday.me/bug/20190612/1227032.html