2012-08-03 56 views
-1

我讀了關於crypt()函數的php.net手冊。這裏是我的代碼:PHP crypt()錯誤

#code..... 
#we retrieve existing salt and password from database 
$salt=$saltquery['salt']; 
#$ex_password - existing password 
$ex_password=$saltquery['pass']; 
#$pass defined earlier. that's input 
$password_hash=crypt($pass, '$2a$07$'.$salt.''); 
if (crypt($password_hash, $ex_password)==$ex_password) { 
#everything is ok 
} else { 
#username/password combination doesn't exists 
$msgText = "Oops! Check your username and password"; 
$pass=NULL; 
} 

我仍然收到錯誤'哎呀!檢查你的用戶名和密碼'。我檢查數據庫和從$password_hash輸出,他們匹配。 也許是更好的像這樣的代碼:

#..... 
if ($password_hash==$ex_password){} 
#..... 

回答

2

您必須將用戶輸入校驗密碼時傳遞給crypt函數(見crypt docs):

if (crypt($user_input, $hashed_password) == $hashed_password) { 
    echo "Password verified!"; 
} 

你是目前正在計算一個新的(不同的)密碼散列,並將其與存儲的密碼進行比較。

+0

我很抱歉這麼奇怪的缺陷 – treng 2012-08-03 17:41:13

+0

所以我不需要在數據庫中存儲鹽? – treng 2012-08-03 17:51:16

+1

不分開。它已經存儲爲密碼摘要的一部分(美元符號之間的最後一部分) – knittl 2012-08-03 17:53:09

2

爲什麼你encryting $ password_hash兩次?

我想你比較會更喜歡這樣的:

$password_hash=crypt($pass, '$2a$07$'.$salt); 
$password_hash_check($ex_password, '$2a$07$' . $salt); 
if ($password_hash === $password_hash_check) { 
#everything is ok 
} else { 
#username/password combination doesn't exists 
$msgText = "Oops! Check your username and password"; 
$pass=NULL; 
} 
+0

你的代碼示例是某種缺陷。也許缺少'= crypt'?即使這樣,它不太可能工作(看文檔) – knittl 2012-08-03 17:29:30

1

我相信這是你想要什麼:

$password_hash=crypt($pass, '$2a$07$'.$salt.''); // crypt input 
if ($password_hash== $ex_password) // check against crypted 
            // password stored in the database