The new password_hash API in PHP 5.5 is nice and I\'d like to start using it everywhere. Given an older project with an older database where passwords are stored in md5 hash
There is very specific use case that has not yet been mentioned here, and that is when you have taken a first step already and began to use crypt
function, but still using MD5 algorithm.
In that case your password hashing at registration/password change would look like:
$pass_hash = crypt($pass, '$1$salthere');
// store $pass_hash in database
And then you would have comparison with:
if(hash_equals($pass_hash_from_db, crypt($user_input, '$1$salthere')))
{
// user logged in
}
The beauty of this transition is that your database would already be in the state ready to use password_verify
.
The registration/password change would become:
$pass_hash = password_hash($pass);
// store $pass_hash in database
And you would substitute comparison with:
if(password_verify($user_input, $pass_hash_from_db))
{
// user logged in
}
This would just work out of the box, and upgrade all user's passwords at next password change. But we don't need to wait, and do what @Fabian did in one's answer here as well.
Here we need to only change the login:
if(password_verify($user_input, $pass_hash_from_db))
{
// user logged in
if(password_needs_rehash($pass_hash_from_db, PASSWORD_DEFAULT))
{
$pass_hash = password_hash($user_input);
// store $pass_hash in database
}
}
This would serve the added benefit of upgrading user's passwords as soon as the new password algorithm will become PHP's default one. You would actually have to do absolutely nothing.
If you wish to use additional parameters for your password hashing function (such as changing the "cost"), you should look at password_hash and password_needs_rehash documentation, pay attention to optional last parameter $options
.