HMAC SHA1 using the same value for key and message

2019-09-17 06:13发布

问题:

I'm working on some C# security code and was about to replace it when I saw that it was using the HMACSHA1 class. The code is used to hash a password for storing in the database. The thing that caught my eye was that it uses the password as the HMAC key which is exactly what is computing the hash for. So is using the data for both the key and the thing your hashing OK? Does this make the security stronger or weaker?

psuedo code:

string pwd = "My~!Cra2y~P@ssWord1#123$";

using (HMACSHA1 hasher = new HMACSHA1())
{
    hasher.Key = encoding.GetBytes(pwd); // using password for the key
    return BytesToHex(hasher.ComputeHash(encoding.GetBytes(pwd))); // computing the hash for the password
}

回答1:

It's about as strong as an unsalted SHA1 hash with two iterations. i.e. pretty weak.

The lack of salt allows an attack to create rainbow tables, or simply attack all password hashes in your database at the same time.

The low iteration count makes the attack fast, since the attacker can simply try more password candidates.

You should add a salt, and use a slower hashing method, such as PBKDF2 and bcrypt. The .net class Rfc2898DeriveBytes implements PBKDF2, so I recommend using that one.



回答2:

I wouldn't recommend HMACSHA1 for database password storage, but setting the Key to be the same as the password does weaken the usefulness of the Key in this purpose. The key is supposed to be secret and used to determine if the underlying hashed data has changed.

For passwords you should be using a SALT+Password combination to increase the security of HASH algorithms. I usually use a SALT that is unique to the user, but not the same as the password, such as the user number or initial registration IP address.

Also, keep in mind that SHA1 is no longer recommended as a hashing algorithm.

You can reference MSDN for a clearer understanding.

This property is the key for the keyed hash algorithm.

A Hash-based Message Authentication Code (HMAC) can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and the HMAC as a single message. The receiver recomputes the hash value on the received message and checks that the computed hash value matches the transmitted hash value.

HMAC can be used with any iterative cryptographic hash function, such as MD5 or SHA-1, in combination with a secret shared key. The cryptographic strength of HMAC depends on the properties of the underlying hash function.

Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated.