Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomNumberGenerator proper usage

Tags:

c#

random

I would like to generate a salt using a secure PRNG. I've read that the newest and recommended way to achieve this is to create a RandomNumberGenerator instance to GetBytes. However, I am not so sure which way should I follow:

// CODE 1

private static byte[] GenerateSaltNewInstance(int size)
{
    using (var generator = RandomNumberGenerator.Create())
    {
        var salt = new byte[size];
        generator.GetBytes(salt);
        return salt;
    }
}

// CODE 2

private static RandomNumberGenerator rng = RandomNumberGenerator.Create();

private static byte[] GenerateSaltStatic(int size)
{
    var salt = new byte[size];
    rng.GetBytes(salt);
    return salt;
}

What is the difference? Basically in the first version of this method I am creating a new instance of RandomNumberGenerator every time. In the second one I am using a static instance initialized once.

Which one should I choose? In articles I see people following the first path, but I don't feel why it would be a better idea to create RandomNumberGenerator 10000 times :P Does it make it more secure to use a new instance each time?

like image 636
Patryk Golebiowski Avatar asked Aug 09 '15 20:08

Patryk Golebiowski


1 Answers

The first method is guaranteed to be thread safe, the 2nd depends on the thread safety of the object returned by the Create() method.

In the current implementation of .NET (as of 2015) it returns RNGCryptoServiceProvider and that type is safe to call GetBytes from multiple threads at the same time but it is not guaranteed that the default Create() will always return a RNGCryptoServiceProvider in future versions of the framework. The safer option is just create it as needed or use RNGCryptoServiceProvider directly and have the guarantee of thread safety.

Security wise they should both be just as secure both call down to the Crypto Service Provider which will just grab the most random number as possible that your hardware supports.

like image 53
Scott Chamberlain Avatar answered Oct 13 '22 10:10

Scott Chamberlain