Fastest implementation of a true random number gen

2019-01-17 17:41发布

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?

8条回答
Explosion°爆炸
2楼-- · 2019-01-17 18:05

AFAIK a true random generator will never be implemented in C#. That can only be done with the help of hardware?

查看更多
\"骚年 ilove
3楼-- · 2019-01-17 18:07

The rule of thumb when it comes to security and cryptography stuff:

Never write your own.

Go with the standard way of doing it and avoid dangerous optimizations.

Edit to address the updated question:

Use Random.Next when you need statistically random numbers not used in security sensitive code and RNGCryptoServiceProvider in security sensitive code. It's not as fast as Random.Next but it has acceptable performance. You should benchmark to see the actual difference. It usually doesn't make sense to sacrifice security for performance.

查看更多
登录 后发表回答