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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With