未使用函数 password_verify 验证密码

2021-12-25 00:00:00 database passwords php mysql mysqli

我想我已经使用函数 PASSWORD 直接从 mysql 数据库中散列密码(我在这里做错了吗?).我正在尝试使用此代码验证该密码:

I think i have hashed password using function PASSWORD directly from mysql database(am i doing wrong here?). And i am trying to verify that password with this code:

    if($submit)
    {
        $first=$_POST['first'];
        $password=$_POST['password'];
        $hash="*85955899FF0A8CDC2CC36745267ABA38EAD1D28"; //this is the hashed password i got by using function PASSWORD in database
        $password=password_verify($password,$hash);
        $db = new mysqli("localhost", "root","","learndb");
        $sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
        $result = $db->query($sql);
        $result=mysqli_num_rows($result);


        if($result>0)
    {

        session_start();
        $_SESSION['logged_in'] = true;
        session_regenerate_id(true);
        header("Location:loginhome.php");

    }
}

但是密码不匹配.我在这里错过了什么?

But the password is not matching. What am i missing here?

更新:

在所有的建议之后,我使用了 php 代码中的 password_hash 来存储到数据库中.

After all the suggestions i have used password_hash from php code to store into database.

$db = new mysqli("localhost", "root","","learndb");
$password=password_hash('ChRisJoRdAn123',PASSWORD_DEFAULT);
$sql="INSERT INTO admin (username,password)values('ChrisJordan','$password')";
$db->query($sql);

密码仍然不匹配.

推荐答案

无法在数据库中搜索加盐密码哈希.要计算散列,您需要使用 password_hash() 函数,因为您已经在插入语句中正确执行了.

One cannot search for a salted password hash in a database. To calculate the hash you need the password_hash() function as you already did correctly in your insert statement.

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);

要检查密码,您首先需要仅按用户名搜索(使用准备好的查询来避免 sql 注入):

To check a password, you first need to search by username only (used a prepared query to avoid sql injection):

$sql = 'select * from admin where username = ?';
$db->prepare($sql);
$db->bind_param('s', $first);

当你最终从数据库中得到存储的哈希值时,可以这样检查:

When you finally got the stored hash from the database, it can be checked like this:

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

相关文章