Using RandomNumberGenerator

I would like to create salt using a secure PRNG. I read that the newest and recommended way to achieve this is to instantiate RandomNumberGenerator

before GetBytes

. However, I am not sure which way I should 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 create a new instance every time RandomNumberGenerator

. In the second, I use a static instance, initialized once.

Which one should you choose? In the articles, I see people following the first path, but I don't feel why it would be better to create RandomNumberGenerator

10,000 times: P Does this make it safer to use a new instance every time?

+3


source to share


1 answer


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

.

In the current .NET implementation, it returns RNGCryptoServiceProvider

, and it is safe to call this type GetBytes

from multiple threads at the same time, but it is not guaranteed that the default Create()

will always return RNGCryptoServiceProvider

in future versions of the structure. The safer option is to simply create it as needed, or use it directly RNGCryptoServiceProvider

and has a thread safety guarantee.



They must of course be both of both of both calls to the Crypto Service Provider , which will capture as much of the most random number as possible your hardware supports.

+6


source







All Articles