Determine if an existing password hash can be upgraded to a stronger algorithm
suggest changeIf you use PASSWORD_DEFAULT, PHP can change the selected algorithm or its cost in a later release. Rehash old passwords when users log in.
<?php
// first determine if a supplied password is valid
if (password_verify($plaintextPassword, $hashedPassword)) {
// True when the hash uses another algorithm, or options that differ
// from the current default (for example a lower bcrypt cost).
if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
// create a new hash with the new default
$newHashedPassword = password_hash($plaintextPassword, PASSWORD_DEFAULT);
// and then save it to your data store
//$db->update(...);
}
}
?>
password_hash(), password_verify(), and password_needs_rehash() have been in PHP since 5.5. If you have to inspect a hash without those functions, a bcrypt hash from password_hash() looks like this:
<?php
if (substr($hashedPassword, 0, 4) == '$2y$' && strlen($hashedPassword) == 60) {
echo 'Algorithm is bcrypt';
// the "cost" determines how strong this version of Bcrypt is
preg_match('/\$2y\$(\d+)\$/', $hashedPassword, $matches);
$cost = $matches[1];
echo 'Bcrypt cost is '.$cost;
}
?>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents