views:

2584

answers:

3

What are the pros and cons of using System.Security.Cryptography.RNGCryptoServiceProvider vs System.Random are. 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:

Pros

  • RNGCryptoServiceProvider is a stronger cryptographically random number, meaning it would be better for determining encryption keys and the likes.

Cons

  • 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.
+3  A: 

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 determinitive PRNG for speed and in simulation.

Charlie Martin
e.g. Blum Blum Shub vs Mersenne Twister. BBS is created with a strong cryptographical proof in mind, and to get anywhere near random for a non-crypto purpose, it's way too slow and resource intensive.
Calyth
Re testing, you can always use Random while testing and change the implementation to use RNGCryptoServiceProvider in production, can't you?
configurator
You can, but a strong PRNG still won't be as suitable for some purposes like Monte Carlo; repeatability and speed are desirable in production use too.
Charlie Martin
A: 

Yes, there is only one more. As Charlie Martin wrote System.Random is faster.

I would like to add the following info:

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.

For all other uses the higher performance of System.Random, and equivalent classes, are welcome.

Jader Dias
+2  A: 

System.Random is not thread safe.

Yury Chaikou
Good point. You can see http://blogs.msdn.com/pfxteam/archive/2009/02/19/9434171.aspx for further discussion.
configurator
Now that I think about it, RNGCryptoServiceProvider isn't either!
configurator
MSDN seems to say that RNGCryptoServiceProvider is thread safe (http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx).
Scott A. Lawrence