Last Updated: February 25, 2016
·
1.206K
· martin_janecek

Hash passwords securely

I believe that you don't store passwords in plain text. But many programmers still store md5 hashed passwords, maybe salted. According to this: http://en.wikipedia.org/wiki/MD5 - some graphics processors can compute 16 to 200 million hashes per second. Also try to Google for md5 salted hash cracker.

MD5 was designed for data integrity checks - calculate file hash, fast plz!

That's why MD5 shouldn't be used for password hashing.

So, how to securely hash passwords? I use this function:

function calculateHash($password, $salt = NULL) {
return crypt($password, $salt ?: '$2a$07$' . Strings::random(22));
}

Now, to get hashed password, call calculateHash($plainpass) and to check password use that hashed password as second parameter:

if($hashedPassFromDb == calculateHash($plainpass, $hashedPassFromDB)){ 
       // correct!
} else {
       // blah!
}

Docs: http://php.net/crypt

Strings::random: http://api.nette.org/2.1.0/source-Utils.Strings.php.html#399-428