PHP和MYSQL:使用bcrypt哈希并与数据库验证密码

7
我正在使用 Andrew Moore 先生的方法(如何在 PHP 中使用 bcrypt 进行密码哈希?)来哈希用户密码。我做的是我有一个注册页面,它使用
$bcrypt = new Bcrypt(12);
$pass = $_POST['password']; //register password field
$hash= $bcrypt->hash($pass);

// then inserts $hash into database with users registered email (I've checked my mysql database and it indeed has an hashed item

接下来是一个登录页面,包括电子邮件和密码字段。我的想法是我的数据库中的电子邮件地址是唯一的。因此,在这种情况下,我编写了一个脚本,首先检查用户的电子邮件地址,然后如果存在,则验证与此相关的哈希密码。

$bcrypt = new Bcrypt(12);

$email = $_POST['email']; //from login email field
$pass_l = $_POST['password']; // from login password field
$hash_1= $bcrypt->hash($pass_1);

$chk_email= $dbh->prepare("SELECT password FROM table WHERE email = ?");
$chk_email -> execute(array($email));

while($row = $chk_email->fetch(PDO::FETCH_ASSOC)){
    $chk_pass = $row['password']; //inside a while loop to get the password
    $pass_isGood = $bcrypt->verify($hash_1, $chk_pass);
    var_dump($pass_isGood); // I'm getting false

}

我不确定我做错了什么,我应该得到true。而且我已经将我的表字段设置为text或者varchar(256)

2个回答

7
使用Andrew Moore的类,你需要调用类中的 verify() 方法来验证用户密码是否与哈希值匹配。你需要传递两个参数:用户输入的明文密码和存储在数据库中的哈希值。
看起来你把第二个哈希密码传递给了 verify() 方法,这就是它无法工作的原因。请将明文密码作为第一个参数传递进去。

4
所以,为了更明确地说明并进一步完善@Michael的答案(因为我也在查看Andrew Moore的解决方案),请执行以下操作:
而不是这样:
$hash_1= $bcrypt->hash($pass_1);
$chk_pass = $row['password']; //inside a while loop to get the password
$pass_isGood = $bcrypt->verify($hash_1, $chk_pass);

you need this:

$pass_l = $_POST['password'];
$chk_pass = $row['password']; //inside a while loop to get the password
$pass_isGood = $bcrypt->verify($pass_l, $chk_pass);
//notice how 1st parameter of verify(is the text input and not its hashed form

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接