I am using same passphrase and salt, yet it produces different keys everytime I run it when using PasswordDerivedBytes. It produces same key everytime if I use Sha1, however. Why is that?
And why does Rfc2898DerivedBytes produce same key everytime if I use that same passphrase, salt, initvector combination, knowing that it uses HMACSha1?
Code snippet added below-
string passPhrase = "passPhrase";
byte[] saltBytes = Encoding.ASCII.GetBytes("saltValue");
int iterations = 2;
int keySize = 32;
string hashAlgo = "HMACSHA1";
Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(passPhrase, saltBytes, iterations);
byte[] keyBytes = derivedBytes.GetBytes(keySize);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltBytes, hashAlgo, iterations);
byte[] keyBytes2 = password.GetBytes(keySize);
Rfc2898DerivedBytes
uses PBKDF2 with HMAC-SHA-1 as PRF (A PRF is essentially a keyed hash). PBKDF2 expects a PRF and uses the key for the password and the salt/chaining value as message.
PasswordDeriveBytes
uses PBKDF1 with a user specified hash algorithm. This hash is expected to be unkeyed. But you passed in "HMACSHA1" which is keyed. When creating an instance of HMACSHA1, .NET fills in a random key. Since PasswordDeriveBytes
is not key aware (it expects an unkeyed hash), it ends up with a differently hash function each time and thus produces different results each time.