我有以下问题/要求。
我的网站有2000个用户,但是密码是使用纯文本存储的(我知道这是超级糟糕的)。通过阅读各种网站博客,我发现我需要使用现代密码哈希和盐。我找到了php-login.net。他们使用现代盐/哈希。
我已经下载了最小的登录脚本,我将在我的网站实现。我已经设置了xampp进行本地测试。当我注册一个用户是哈希密码,我可以登录。
我的主要要求是我想散列所有我当前的纯文本密码。PHP登录使用PHP密码兼容库。
password_compatibility_library
如何对数据库中所有的普通密码进行哈希,因为我不打算对2000进行1乘1的哈希。
我假设我可以写一个脚本,将使用密码库更新数据库中的所有记录。
<?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
列中的密码,而不是原始密码。如果一切正常,你可以登录没有问题,你可以删除原来的密码列,你就完成了。
PHP现在有一个hash_password()函数使用BCrypt。
这应该很容易编写几行脚本。
foreach($users as $user) {
$hashed = password_hash($user->password, PASSWORD_DEFAULT);
echo "Hashed user {$user->id}'n";
// Do db query here
}
也看看password_verify() !