问题描述
使用 System.Security.Cryptography.RNGCryptoServiceProvider
与 System.Random
的优缺点是什么.我知道 RNGCryptoServiceProvider
是更随机的",即对于黑客来说更难预测.还有其他优点或缺点吗?
What are the pros and cons of using System.Security.Cryptography.RNGCryptoServiceProvider
vs System.Random
. I know that RNGCryptoServiceProvider
is 'more random', i.e. less predictable for hackers. Any other pros or cons?
更新:
根据回复,以下是目前使用 RNGCryptoServiceProvider
的利弊:
According to the responses, here are the pros and cons of using RNGCryptoServiceProvider
so far:
RNGCryptoServiceProvider
是一个更强的加密随机数,这意味着它更适合确定加密密钥等.
RNGCryptoServiceProvider
is a stronger cryptographically random number, meaning it would be better for determining encryption keys and the likes.
Random
更快,因为它是一个更简单的计算;当在加密随机性不重要的模拟或长时间计算中使用时,应该使用它.注意:有关模拟的详细信息,请参阅 Kevin 的回答 -Random
不一定足够随机,而且您可能想要使用不同的非加密 PRNG.
Random
is faster because it is a simpler calculation; when used in simulations or long calculations where cryptographic randomness isn't important, this should be used. Note: see Kevin's answer for details about simulations -Random
is not necessarily random enough, and you may want to use a different non-cryptographic PRNG.
推荐答案
加密强的 RNG 会变慢 --- 它需要更多的计算 --- 并且会是光谱白色,但不太适合模拟或 Monte Carlo 方法,因为它们确实需要更多时间,而且因为它们可能不可重复,这对测试很好.
A cryptographically strong RNG will be slower --- it takes more computation --- and will be spectrally white, but won't be as well suited to simulations or Monte Carlo methods, both because they do take more time, and because they may not be repeatable, which is nice for testing.
一般来说,当您想要像 UUID 这样的唯一数字或作为加密的密钥时,您想要使用加密 PRNG,以及用于速度和模拟的确定性 PRNG.
In general, you want to use a cryptographic PRNG when you want a unique number like a UUID, or as a key for encryption, and a deterministic PRNG for speed and in simulation.
这篇关于RNGCryptoServiceProvider 的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!