Jonathan Wood
Jonathan Wood

Reputation: 67251

RNGCryptoServiceProvider.GetBytes() returns all zeros

I'm using the following code to generate an encryption salt.

TripleDES tripleDES = TripleDES.Create()
tripleDES.IV = new byte[8];

using (RNGCryptoServiceProvider rngProvider = new RNGCryptoServiceProvider())
{
    rngProvider.GetBytes(tripleDES.IV);
}

Rfc2898DeriveBytes keyBytes = new Rfc2898DeriveBytes(Password, tripleDES.IV);
tripleDES.Key = keyBytes.GetBytes(16);

But after calling GetBytes(), I can see that tripleDES.IV contains all zeros.

That certainly doesn't seem as random as the documentation suggests.

Upvotes: 2

Views: 184

Answers (1)

nollidge
nollidge

Reputation: 2191

Looking at the source for SymmetricAlgorithm (the base class for TripleDES), the IV property returns a clone of the current IV byte array, so rngProvider.GetBytes() is setting the bytes on a clone array, not the actual one.

You don't need to set the IV to a random value anyway - it will be initialized to one already after calling TripleDES.Create(). And if you want a new one for some reason, you can just call GenerateIV() which will set IV to a new random value.

Upvotes: 3

Related Questions