【问题标题】:PHP & MYSQL: using bcrypt hash and verifying password with databasePHP 和 MYSQL:使用 bcrypt 哈希并使用数据库验证密码
【发布时间】:2012-07-13 22:28:43
【问题描述】:

我正在使用 Andrew Moore 先生的方法 (How do you use bcrypt for hashing passwords in PHP?) 对用户密码进行哈希处理。我所做的是我有一个注册页面,它使用

$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

}

我不确定我做错了什么,我应该是真的。我已经将我的表域设置为text 甚至varchar(256)

【问题讨论】:

    标签: php mysql hash passwords bcrypt


    【解决方案1】:

    使用Andrew Moore's class,需要调用类verify()方法来验证用户密码是否与hash匹配。您传递给它的两个参数是用户输入的明文密码和您存储在数据库中的哈希值。

    您似乎将第二个哈希密码传递给了verify(),这就是它不起作用的原因。将明文密码作为第一个参数传入。

    【讨论】:

      【解决方案2】:

      所以要明确并以@Michael 的回答为基础(因为我也在查看Andrew Mooore's 解决方案):

      而不是这个:

      $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);
      

      你需要这个:

      $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
      

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 2016-06-06
        • 1970-01-01
        • 2017-12-13
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        相关资源
        最近更新 更多