开发者

How to implement hash_hmac properly?

Reading this excellent answer about password hashing and wondering how to implement it:

The Wicked Flea wrote:

Generate a nonce for each user; this alone defeats the rainbow table. This is a random number that, depending on the range, expands how many resulting hashes there are.

So beside users' password store a unique token in my datab开发者_如何学JAVAase?

The example code in the original post:

function hash_password($password, $nonce) {
  global $site_key;
  return hash_hmac('sha512', $password . $nonce, $site_key);
}

How can i verify a password with this code? Let me explain:

When user submits his password i need to generate it's hash to check for an existing database row where email address and hashed password match. How can i select this row when i know nothing about users' $nonce? Am i missing something? Maybe i need to select user by only his e-mail address then verify the password hash later?

Btw, do you recommend this hashing method?


I think you have nailed the idea. The same concept is applied in general UNIX-style salted passwords - store salt in clear text with password and retrieve it by username, then use the salt and provided password to produce new hash to be compared to the stored value.

It is up to you to consider wether you trust your DB server (and the connection to it) to use a hashing algorithm that is supported by the DB and let the DB do the math:

SELECT * FROM users WHERE email = 'email' AND password = SHA1(CONCAT('cleartextpass',nonce));

Or you could do the math in the code after retrieving all the matching emails.

EDIT: The ThiefMaster comment on differentiating between missing user and invalid password is classical security flaw, which allows attackers to acquire a list of valid usernames and concentrate on breaking their passwords instead of fishing in the darkness. I would strongly recommend against it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜