确定现有密码哈希是否可以升级为更强大的算法
如果你使用 PASSWORD_DEFAULT
方法让系统选择最佳算法来散列你的密码,因为默认值增加,你可能希望在用户登录时重新使用旧密码
<?php
// first determine if a supplied password is valid
if (password_verify($plaintextPassword, $hashedPassword)) {
// now determine if the existing hash was created with an algorithm that is
// no longer the default
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_ *函数(并且你无法使用下面备注中链接的兼容包),则可以确定算法并使用类似于以下方法创建原始哈希:
<?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;
}
?>