2012-07-05 147 views
1

好的,所以下面的所有代碼都不是我自己的。我一直在關注互聯網上的教程,但是當我嘗試並運行它時,沒有看到任何密碼匹配。我相信,在密碼中添加密碼可能會有錯誤,因爲數據庫中的密碼遠不及login.php腳本中描述的64個字符。我不知道。代碼如下:哈希/鹽漬時密碼不匹配

register.php

// Create a 256 bit (64 characters) long random salt 
// Let's add 'something random' and the username 
// to the salt as well for added security 
$salt = hash('sha256', uniqid(mt_rand(), true) . 'something random' . strtolower($username)); 

// Prefix the password with the salt 
$hash = $salt . $password; 

// Hash the salted password a bunch of times 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

// Prefix the hash with the salt so we can find it back later 
$hash = $salt . $hash; 

// carry on with registration code... 

的login.php

$email = $_POST['email']; 
$password = $_POST['password']; 

$con = mysql_connect("localhost", "redacted", "redacted", "redacted"); 

$sql = ' 
    SELECT 
     `password` 
    FROM `users` 
     WHERE `email` = "' . mysql_real_escape_string($email) . '" 
    LIMIT 1 
    ;'; 

$r = mysql_fetch_assoc(mysql_query($sql)); 

// The first 64 characters of the hash is the salt 
$salt = substr($r['password'], 0, 64); 

$hash = $salt . $password; 

// Hash the password as we did before 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

$hash = $salt . $hash; 

if ($hash == $r['password']) 
{ 
    session_start(); 
    header('Location: /quiz/index.php'); 
} 

if($hash != $r['password']){ 
    session_start(); 
    header('Location: /?error=4'); 
} 

// end login script 
+0

哪個教程? PHP在網上有很多低劣的教程。這似乎是其中之一。 – alex

+3

常見的錯誤是數據庫字段長度不足以存儲所有字符。 – Konerak

+0

啊......這就是爲什麼。我的密碼字段只有30個字符。歡呼@Konerak :-) –

回答

2

一個常見的錯誤是當數據庫字段不夠長時存儲所有字符。那麼密碼將永遠不會與用戶輸入的內容相同。

對於這種功能,總是寫單元測試,檢查函數(仍然)是否按預期工作。有一天,有人會修改數據庫,更改散列算法,修改鹽......沒有人能夠登錄。

-1

它看起來像您要添加的鹽2次:

$hash = $salt . $password; 

// Hash the password as we did before 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

//skip the below one 
$hash = $salt . $hash; 

更新:

事實上,在這種情況下需要添加鹽2次。

儘管鹽應該保存在一個單獨的數據庫列中,所以代碼將更加簡化 - 通過避免所有字符串連接來存儲/檢索salt。

除此之外,您的數據庫結構將更接近第三範式通過將每條信息存儲在一個單獨的插槽中。

+3

跳過整個「無數次哈希」。只要使用可引入工作因素的東西,通常建議使用bcrypt。 – alex

+2

你需要存儲鹽與散列,以便你可以知道它是什麼後。 –

+0

事實證明,我的密碼數據庫字段太短。但感謝所有的建議。 –