2015-02-23 104 views
1

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

下面是摘录的代码存储在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!"; 
} 
+0

你确定这是正确的哈希? – 2015-02-23 03:51:26

+0

虽然我注意到每次刷新我的测试页时$ hash2变量都会改变,但我并不是100%确定crypt如何工作以充分理解原因。 – mattdonders 2015-02-23 03:53:39

回答

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

+0

了解,但'password_verify'应该能够验证任何由该密码生成的哈希值是否正确? – mattdonders 2015-02-23 04:00:25

+0

@mattdonders我什么东西是错误的哈希。我创造了一个新的哈希和我的作品完美。尝试用我的散列更新记录(如果我的例子为你崇拜),并让我知道如果你有其他东西。 – 2015-02-23 04:07:11

+0

但是有什么可能是错的?哈希长度相同,我也使用'bind_param()'进行VARCHAR(255)的INSERT操作。该测试文件中的$ hash是直接从thr数据库中获得的。 – mattdonders 2015-02-23 04:08:32

相关问题