如果我使用HMACSha1作为散列算法,为什么PasswordDerivedBytes每次都会生成不同的密钥?

Thu*_*uck 2 c# encryption cryptography encryption-symmetric

我使用相同的密码和盐,但每次运行PasswordDerivedBytes时它都会生成不同的密钥.但是,如果我使用Sha1,它每次都会产生相同的密钥.这是为什么?

如果我使用相同的密码,salt,initvector组合,知道它使用HMACSha1,为什么Rfc2898DerivedBytes每次产生相同的密钥?

以下代码摘要 -

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);
Run Code Online (Sandbox Code Playgroud)

Cod*_*aos 5

Rfc2898DerivedBytes使用PBKDF2和HMAC-SHA-1作为PRF(PRF本质上是一个键控哈希).PBKDF2需要一个PRF并使用密钥和salt/chaining值作为消息.

PasswordDeriveBytes使用PBKDF1和用户指定的哈希算法.此哈希应该是未加密的.但是你传入了键入的"HMACSHA1".在创建HMACSHA1实例时,.NET会填充随机密钥.由于PasswordDeriveBytes不知道密钥(它需要一个无键的哈希),它每次都会以不同的哈希函数结束,因此每次都会产生不同的结果.