将 md5 密码哈希转换为 PHP 5.5 password_hash()转换为、密码、password_hash、PHP

2023-09-06 22:55:56 作者:稍微。

PHP 5.5 中的新 password_hash API 很不错,我想开始在任何地方使用它.给定一个具有旧数据库的旧项目,其中密码存储在 md5 哈希中,将旧用户密码迁移到新的、更安全的 API 的最佳方法是什么?

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 hashes, what is the best way to go about migrating old user passwords to the new, more secure API?

除了简单地提示用户在下次登录时重置密码(这对用户来说是不切实际且烦人的)之外,我还考虑过使用当前的 md5 哈希作为我所有现有用户的 password_hash() 输入的可能性.要验证这些用户的密码(在登录期间),我会将他们的输入转换为 md5 哈希,然后将其用于 password_verify().新用户可以省去这个额外的步骤.

Apart from simply prompting users to reset their password upon next login (this is impractical and annoying for users) I've thought about the possibility of using current md5 hash as the input to password_hash() for all my existing users. To verify passwords for these users (during login), I'd convert their input to an md5 hash and then use that to password_verify(). New users would be spared this extra step.

这是一个值得的方法吗?有没有更好的透明迁移方法,让用户不必担心密码重置,但我可以立即享受更安全的散列带来的好处?

Is this a worthwhile way to go about this? Are there any better ways for transparent migration in which users are not nagged about password resets yet I can immediately enjoy the benefits of more secure hashing?

最重要的是,采用现有的 md5 哈希(容易被暴力破解)并使用 password_hash() API 对其进行双重哈希"是否有安全优势?

Most importantly, is there even a security benefit in taking existing md5 hashes (which are prone to brute force) and using the password_hash() API to "double-hash" it?

推荐答案

在您的 login.php (?) 中将旧密码从 MD5 转换为 bcrypt 并替换数据库中旧的 MD5 哈希用新的.

In your login.php (?) you convert the old passwords from MD5 to bcrypt and replace the old MD5 hash in the database with the new one.

伪代码:

$password = $_POST["password"];

if (substr($pwInDatabase, 0, 1) == "$")
{
    // Password already converted, verify using password_verify
}
else
{
    // User still using the old MD5, update it!

    if (md5($password) == $pwInDatabase)
    {
        $db->storePw(password_hash($password));
    }
}

双重哈希不会增加 bcrypt 的安全性,因为 bcrypt itsef 是一种单向哈希函数.

Double hashing would not increase the security of bcrypt, as bcrypt itsef is a one-way hashing function.

注意:MD5 生成 32 个字符长度的字符串,而 password_hash() 最少为 60.

Nota: MD5 produces a 32 character length string, while password_hash() is a minimum of 60.

阅读手册:

http://php.net/manual/en/function.password-hash.php

如果您决定使用 password_hash() 或兼容包(如果 PHP