Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

performance - Fastest implementation of a true random number generator in C#

I was reading about Random.Next() that for "cryptographically secure random number suitable for creating a random password" MSDN suggests RNGCryptoServiceProvider Class

What the speed penality? There is some fastest way to get true random numbers?

EDIT: With Random.Next() I get a new random number. And with...

byte[] randomNumber = new byte[1];
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
Gen.GetBytes(randomNumber);
int rand = Convert.ToInt32(randomNumber[0]);

I get a "cryptographically secure random number" I want know if the above code is fast compared with "Random.Next()" and if there is some fast way to get same results, ok?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest way to answer your question might be to turn your question upside down.

Assume that the CryptoServiceProvider implementation holds all the advantages. It is just as fast and uses just as little memory as Random.Next.

Then why do both implementations exist? Why do we even Have Random.Next in the framework?

Look at what we know about each implementation. One generates cryptographically secure random number, the other makes no promises.

Which is simpler? Generating random numbers that are sufficiently random to be used in cryptography, or generating numbers that simply "look" random, but don't guarantee anything else? If there wasn't a cost associated with generating cryptographically secure random numbers, then every random number generator would do it.

You can usually assume that standard library functions are designed to do what it says on the box and do it well. Random.Next is designed to get you the next random number in a sequence of pseudo-random numbers as efficiently as possible.

CryptoServiceProvider is designed to generate random numbers strong enough to be used in cryptography, and do that as efficiently as possible. If there was a way to do this as efficiently as Random.Next, then Random.Next would use it too.

Your question seems to assume brain damage on the part of the framework designers - that they somehow designed a needlessly slow function to generate cryptographically secure random numbers, even though there was a faster way.

The fastest way to generate cryptographically secure random numbers is most likely to call the function designed by experts to generate cryptographically secure random numbers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...