php – 密码未使用函数password_verify验证

我想我直接从mysql数据库使用函数PASSWORD散列密码(我在这里做错了吗?).我试图用这段代码验证密码:

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

    }
}

但密码不匹配.我在这里失踪了什么?

更新:

完成所有建议之后我用php代码中的password_hash来存储到数据库中.

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

密码仍然不匹配.

解决方法:

无法在数据库中搜索salted密码哈希.要计算哈希值,您需要使用password_hash()函数,就像在insert语句中已正确执行的那样.

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

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

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

当您最终从数据库中获取存储的哈希时,可以像这样检查它:

// 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);
上一篇:用于强密码验证的PHP正则表达式


下一篇:Android:用户登录并保持会话直到注销(需要批准)