Fastest implementation of a true random number generator in C#

前端 未结 8 1204
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 23:23

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

8条回答
  •  攒了一身酷
    2020-12-08 23:42

    The "cryptographically secure random number" generated by your example code will only ever be between 0 and 255 inclusive!

    If you want to return all possible Int32 values then you should use 4 random bytes. Your code should look something like this:

    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] rndBytes = new byte[4];
    rng.GetBytes(rndBytes);
    int rand = BitConverter.ToInt32(rndBytes, 0);
    

    A quick benchmark on my (old-ish) machine suggests that Random.Next is approximately 200x faster than using RNGCryptoServiceProvider.

提交回复
热议问题