Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and cons of RNGCryptoServiceProvider

Tags:

c#

.net

random

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:

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. 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.
like image 303
configurator Avatar asked Jan 07 '09 01:01

configurator


People also ask

Is RNGCryptoServiceProvider secure?

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.

Is RNGCryptoServiceProvider obsolete?

RNGCryptoServiceProvider is marked as obsolete, starting in . NET 6.

Is RNGCryptoServiceProvider thread safe?

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.

What is RNGCryptoServiceProvider?

RNGCryptoServiceProvider.GetBytes Method (System.Security.Cryptography) Fills an array of bytes with a cryptographically strong sequence of random values.


2 Answers

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.

like image 69
Charlie Martin Avatar answered Oct 12 '22 23:10

Charlie Martin


System.Random is not thread safe.

like image 32
Yury Chaikou Avatar answered Oct 12 '22 23:10

Yury Chaikou