简体   繁体   English

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

[英]PHP & MYSQL: using bcrypt hash and verifying password with database

I'm using Mr. Andrew Moore's method ( How do you use bcrypt for hashing passwords in PHP? ) of hashing user's password. 我正在使用Andrew Moore先生的方法( 如何使用bcrypt在PHP中使用哈希密码? )哈希用户的密码。 What I did is I have a registration page and it uses 我做的是我有一个注册页面,它使用

$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

Then I have a login page, consisting of email and password fields. 然后我有一个登录页面,包括电子邮件和密码字段。 My thought is that email addresses are unique in my database. 我的想法是电子邮件地址在我的数据库中是唯一的。 So with that in mind, I made a script where it check's users email address first, then if there is an existing one, verify the hash password with this 因此,考虑到这一点,我创建了一个脚本,首先检查用户的电子邮件地址,然后如果有现有的,请用此验证哈希密码

$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

}

I'm not sure what I'm doing wrong, I'm supposed to get true. 我不确定我做错了什么,我应该成真。 And I have set my tablefield to text or even varchar(256) 我已将tablefield设置为text或甚至varchar(256)

Using Andrew Moore's class , you need to call the class verify() method to verify that the user's password matches the hash. 使用Andrew Moore的类 ,您需要调用类verify()方法来验证用户的密码是否与哈希匹配。 The two parameters you pass to it are the plaintext password the user entered and the hash that you stored in the database. 传递给它的两个参数是用户输入的明文密码和存储在数据库中的哈希值。

It seems you passed a second hashed password to verify() instead, which is why it's not working. 看来你传递了第二个哈希密码来verify() ,这就是为什么它不起作用。 Pass in the plaintext password as the first argument. 传入明文密码作为第一个参数。

So just to be explicit and build upon @Michael's answer (since I was looking over Andrew Mooore's solution too): 所以只是要明确并建立@ Michael的回答(因为我也在查看Andrew Mooore的解决方案):

instead of this: 而不是这个:

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM