2

我有以下问题/要求。

我的网站有 2000 个用户,但是密码是使用纯文本存储的(我知道这非常糟糕)。通过阅读各种网站博客,我发现我需要使用现代密码散列和加盐。我找到了 php-login.net。他们使用现代盐渍/散列。

我已经下载了我将在我的网站中实现的最小登录脚本。我已经设置 xampp 在本地进行测试。当我注册用户时,会散列密码,我可以登录。

我的主要要求是我想散列我当前所有的纯文本密码。使用 php 密码兼容性库的 php 登录。

密码兼容性库

我如何散列数据库中的所有普通密码,因为我不会将 2000 1 逐 1 散列。

我假设我可以编写一个脚本,使用密码库更新数据库中的所有记录。

4

2 回答 2

3
<?php
// you should put your db connection stuff here
require('connect.php'); 

//you create a new column to store hashed passwords. Good idea if
//something goes bad. You should drop the column with the original
// passwords once every thing is ok and done.
$result = mysqli_query(
    $conn,
    'alter table users add column hashed_password varchar(255) not null'
); 

if ($result===FALSE)
{
// handle error here
}

$result = mysqli_query($conn, 'select * from users');
if ($result===FALSE)
{
// handle error here
}else
{
    while($user = mysqli_fetch_assoc($result)
    {
        // you could use PASSWORD_DEFAULT here but I wouldn't. If in a
        // future migration the default password crypt function changes
        // your system won't work and it will be hard to know why.
        $hashedPassword = password_hash($user['password'], PASSWORD_BCRYPT);
        $result2 = mysqli_query($conn,'update users set hashed_password = \''. mysqli_real_escape_string($hashedPassword) .'\' where id=\''. $user['id'] .'\'');
        if ($result2 === FALSE)
        {
        //handle error here
        }
    }
}

然后您只需检查hashed_password列中的密码而不是原始密码。如果一切正常并且您可以登录没有问题,您可以删除原始密码列,您就完成了。

于 2015-06-03T10:07:33.337 回答
2

PHP 现在有一个使用 BCrypt 的hash_password()函数。

这应该很容易用几行编写脚本。

foreach($users as $user) {
    $hashed = password_hash($user->password, PASSWORD_DEFAULT);
    echo "Hashed user {$user->id}\n";
    // Do db query here
}

看看password_verify()呢!

于 2015-06-03T09:55:22.517 回答