2014-06-07 51 views
-1

在我的註冊頁面上,我使用了SHA1和salt來將我的密碼存儲在數據庫中。我想我已經正確地做了這個,因爲當我檢查數據庫中包含的salt時。這是我做到的。記錄鹽和散列問題

$newPassword = $_POST['Password'] ; 
    if (!empty($newPassword)) { 
    //Escape bad characters 
    //$newuser = mysql_real_escape_string($newuser); 
    //remove leading and trailing whitespace 
    $newPassword = trim($newPassword); 
    $newPassword = sha1($newPassword); 
    $salt = '-45dfeHK/[email protected]/klF21-1_\/4JkUP/4'; 

} 
else die ("ERROR: Enter a Password"); 

和輸入

$query = "INSERT INTO members (memberFirstname, memberSecondname, memberEmailaddress, memberPassword, memberAddress, memberPostcode) VALUES ('$newFirstName', '$newSecondName', '$newEmailAddress', '$newPassword$salt', '$newAddress', '$newPostcode')"; 

,當我嘗試登錄我的問題奠定。我不確定如何刪除鹽和取消密碼(如果這是需要做的)。我可以輸入電子郵件地址並將散列和鹽粘貼到密碼字段中,並可以成功登錄。

這是我的腳本登錄。

<?php 
include 'db.inc'; 
session_start(); 
$UserEmail =$_POST["EmailAddress"]; 
$UserPassword =$_POST["Password"]; 
$query = "SELECT * FROM members WHERE memberEmailaddress = '$UserEmail' 
     AND memberPassword = '$UserPassword' "; 

$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!"); 
mysql_select_db($databaseName) or die ("Unable to select database!"); 
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
// see if any rows were returned 
if (mysql_num_rows($result) > 0) { 
    $_SESSION["authenticatedUser"] = $UserEmail; 
    // Relocate to the logged-in page 
    header("Location: Index.php"); 
} 
else 
    { 
    $_SESSION["message"] = "Could not connect log in as $UserEmail " ; 
    header("Location: Login.php"); 
    }  
mysql_free_result($result); 
mysql_close($connection); 

?> 
+1

請使用此代替http://docs.php.net/manual/en/ref.password.php – PeeHaa

+1

另請參閱http://stackoverflow.com/questions/60174/how-can-i-prevent-sql -injection-in-php – PeeHaa

+1

你使用的是錯誤的salt,並且你選擇了一個不適當的哈希函數來保護密碼。你不應該試圖自己做這些東西。使用現成的庫,安全性非常重要,不會讓這些東西錯誤,而且你會**錯誤。正確存儲密碼是一個衆所周知的難題。 – meagar

回答

1

有幾個問題你的方法。首先你根本不使用鹽,它會被儲存但不被使用。其次鹽對每個密碼應該是唯一的,在你的情況下使用靜態鹽,這實際上是一種胡椒而不是鹽。進一步你使用一個快速哈希算法,但這可能是蠻力的方式太快,而你應該切換到像BCrypt或PBKDF2成本因素的哈希算法。

PHP已經具備了良好的功能散列密碼(也許你需要的compatibility pack):

// Hash a new password for storing in the database. 
// The function automatically generates a cryptographically safe salt. 
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT); 

// Check if the hash of the entered login password, matches the stored hash. 
// The salt and the cost factor will be extracted from $existingHashFromDb. 
$isPasswordCorrect = password_verify($password, $existingHashFromDb); 

因爲這個函數生成自身的安全鹽和其附加到所產生的哈希值,你不能直接用SQL檢查密碼。相反,你做一個查詢來獲取存儲的哈希(通過用戶名),然後你可以驗證輸入的密碼與存儲的。我寫了一個tutorial,我試圖解釋更深入的重要觀點。