如何将输入的密码与数据库中的散列密码相匹配?

How to match a inputted password to hashed password from database?

出于某些原因,我不知道我是否真的从数据库中获取了散列密码,或者我是否正在将它与输入的密码进行比较。我已经使用 password_hash 方法成功测试了我的注册,我在数据库中看到了散列密码。

我还应该对输入的密码进行散列处理,以便与数据库中的散列密码进行比较吗?或者我的查询是错误的?请帮忙!!!谢谢!

<?php
require "../connection.php";

session_start();

    if(isset($_POST['login'])) {

    $username = stripslashes($_POST['username']);
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = stripslashes($_POST['password']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    $query = mysqli_query ($conn, "SELECT * FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
    $reader = mysqli_num_rows($query);

        if ($reader == 1) {
            $passwordQuery = mysqli_query ($conn, "SELECT password FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
            $row = mysqli_fetch_array($passwordQuery);
            $hashedPasswordFromDb = $row['password'];
            if (password_verify($password, $hashedPasswordFromDb)) {
                $query = mysqli_query ($conn, "SELECT id, student_number FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
                $row = mysqli_fetch_array($query);
                $id = $row['id'];
                $student_number = $row['student_number'];
                $sesData = array('id' => $id, 'student_number', $student_number);
                $_SESSION['ses_account'] = $sesData;
                mysqli_query ($conn, "UPDATE admin SET lastLogin=NOW() WHERE student_number='$student_number'");
                header("location: dashboard.php");
            } else {
                $msg="User not recognized. Please try again.";
                urlencode($msg);
                header("location: ../index.php?errmsg=$msg");
            }
        } else {
            $msg="User not recognized. Please try again.";
            urlencode($msg);
            header("location: ../index.php?errmsg=$msg");
        }
    }
?>

我假设您将散列密码存储到数据库中(这很好)

但在这里:

$query = mysqli_query ($conn, "SELECT * FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));

您正在获取用户,将哈希密码与 plain-text 密码进行比较。所以查询永远不会 return any row/user.


您应该如何着手实施非常基本的系统,用于1注册用户和2 检查登录。

首先使用 prepared statements 而不是清理输入,然后将字符串注入查询。您最终会得到 更安全 和更易读的代码。

1 当您注册一个新用户时,将用户名和散列(可能 salted)密码存储到分贝

2 当您检查登录时,hash/elaborate 您作为输入获得的纯文本密码(与 相同的过程您在执行注册时实施)然后制作一个 SELECT 以通过用户名获取用户,最后检查散列密码匹配。


假设你至少在 PHP 5.5 使用 password_hash and password_verify 散列密码 (password_hash) 并用散列密码检查明文密码 (password_verify )

进一步阅读:Secure hash and salt for PHP passwords