2015-02-23 101 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

相關問題