【问题标题】:How to Compare BCRYPT Hashed Passwords in PHP如何在 PHP 中比较 BCRYPT 哈希密码
【发布时间】:2019-11-11 15:18:09
【问题描述】:

我有一个 HTML 格式的“创建新用户”表单,需要知道其中的某些部分需要验证和检查(PHP 或 javascript),以及最好的解决方法。

密码处理在 PHP 中完成,检查给定用户名是否可用或已存在于数据库中的代码也是如此。需要知道比较“密码”和“确认密码”字段的最佳位置,因为在 PHP 中对两者进行哈希处理时似乎很难做到。

if ($_SERVER["REQUEST_METHOD"] == "POST") { // If the form is submitted and by the method of post
    $new_username = test_input($_POST['new_username']); // Set new_username to the new_username value from the form
    $new_password = password_hash(test_input($_POST['new_password']), PASSWORD_DEFAULT); // Get the new_password from the form and hash it before passing to the variable
    $confirm_password = password_hash(test_input($_POST['new_password_confirm']), PASSWORD_DEFAULT); // Get the confirm_password field from the form and hash it
    $team = $_POST['new_team']; // Get the new_team field (doesn't need validation as it is a dropdown choice)
    $username_valid = test_account_validity($newConnection, $new_username);
    if ($username_valid) {
        echo "";
    }
    if (hash_equals($new_password, $confirm_password)) {
        echo "Passwords Match";
    }
    else {
        echo "Passwords Dont Match";
    }
}

function test_input($data) { // Function to remove spaces, slashes and special html characters before returning the valid data
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

当密码在散列之前相同(在两个表单字段中输入相同)但它说密码不匹配时,预期密码匹配输出。

编辑

与如何使用密码散列不同,因为这是关于将两个输入密码的散列相互比较,而不是将字符串与散列或散列进行比较以存储在数据库中。

【问题讨论】:

  • 这不是hash_equals 所做的。再次链接密码哈希的基本介绍会有所帮助吗?
  • @mario 如果你有一个真正有帮助的,我想我只是有点困惑。谢谢
  • 为什么不简单地比较密码并在它们匹配后对其进行哈希处理?此外,您不应编辑用户密码。如果存在不允许的字符,最好通知用户密码无效,而不是更改密码。
  • @ich5003 这不会让它面临时间错误。在那种情况下,我仍然使用 hash_equals
  • 我将使用以下行为: 1. 比较 POST[pass] 和 POST[pass_verify],如果它们匹配,则对其进行哈希处理并使用它。在您的登录方法中,您将使用 password_verify,因为 password_hash 使用盐,因此两次散列相同的密码不会产生相同的结果。见这里:php.net/manual/de/function.password-hash.php

标签: php hash passwords password-protection


【解决方案1】:

用户登录的场景是

  1. 从html中获取用户名和密码
  2. 从数据库中获取与用户名匹配的用户数据
  3. 传递来自用户输入的纯密码和来自 数据库到password_verify函数,如果它返回true它 表示密码正确否则密码错误

请参阅文档php.net

【讨论】:

  • 登录没问题,但我更多的是查看密码并确认密码字段以检查它们是否匹配
  • 您在散列之前确认它们是否相同,然后您散列 POST['password'] 并将其保存到数据库中,password_hash 函数每次生成散列时都会生成随机字符串将其放入等式中意味着每次你通过password时它都会产生不同的has,即使它是同一个
猜你喜欢
  • 1970-01-01
  • 2017-09-19
  • 2019-09-12
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多