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?
UPDATE:
According to the responses, here are the pros and cons of using RNGCryptoServiceProvider
so far:
RNGCryptoServiceProvider
is a stronger cryptographically random number, meaning it would be better for determining encryption keys and the likes.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.The RNGCryptoServiceProvider is the default implementation of a security standards compliant random number generator. If you need a random variable for security purposes, you must use this class, or an equivalent, but don't use System. Random because it is highly predictable.
RNGCryptoServiceProvider is marked as obsolete, starting in . NET 6.
Yes. It's in the "remarks" section: The length of the byte array determines how many cryptographically strong random bytes are produced. This method is thread safe.
RNGCryptoServiceProvider.GetBytes Method (System.Security.Cryptography) Fills an array of bytes with a cryptographically strong sequence of random values.
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.
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.
System.Random
is not thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With