確定現有密碼雜湊是否可以升級為更強大的演算法

如果你使用 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;
}
?>