PHP password_hash和password_verify不能使用MySQL

时间:2015-02-23 03:43:15

标签: php mysql password-hash

我使用password_hash将密码存储在VARCHAR(255)类型的MySQL数据库字段中。当我尝试登录用户并验证凭据时,password_verify函数始终返回false。

以下是将密码存储在MySQL数据库中的代码摘录:

$password_hash = password_hash($password, PASSWORD_DEFAULT);

// Generate API Key
$api_key = $this->generateApiKey();

// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();

检查密码的代码:

// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

$stmt->bind_result($password_hash);
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Found user with that email address
    // Now verify the password

    $stmt->fetch();
    $stmt->close();

    if (password_verify($password, $password_hash)) {
        // User password is correct
        return TRUE;

然后我编写了这个测试代码并直接从MySQL字段中获取数据,但它仍然失败。当我在同一个文件中创建password_hash时(下面的文件中为$ hash2) - 然后密码验证正确。

$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);

echo $hash . " - " . strlen($hash);
echo "<br />";
echo $hash2 . " - " . strlen($hash2);
echo "<br />";

if (password_verify($password, $hash)) {
    echo "Password Valid!";
} else {
    echo "Password invalid!";
}

echo "<br /><br />";

if (password_verify($password, $hash2)) {
    echo "Password 2 Valid!";
} else {
    echo "Password 2 invalid!";
}

2 个答案:

答案 0 :(得分:1)

这证明你的哈希值有问题

<?php
// See the password_hash() example to see where this came from.
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';

$hash2 = '$2y$10$gMJKYZUc1FKSZBnsONxLOebOHj.uuEWSiCP0jo4Zv0iAHBz6iz.NG';

if (password_verify('pass1234567890', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

echo "<br>";

if (password_verify('pass1234567890', $hash2)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

截图enter image description here

答案 1 :(得分:-1)

只需为if(password_verify($pass_input, $pass_db))设置变量 其中$pass_input是从文本形式给出的值,$pass_db是存储在mysql中(已散列)的值

赞:

$verif_pass = (password_verify($pass_input, $pass_db));
if($verif_pass){echo "TRUE"} else {echo "FALSE";}

,然后根据需要修改TRUE / FALSE。