2014-03-04 202 views
2

我已經通過網絡搜索過,發現哈希密碼的函數。但
我有麻煩處理存儲在數據庫中的散列密碼。我正在使用的函數會生成隨機密碼,因爲它與隨機生成的鹽級聯在一起。 用戶想要更改密碼時出現問題。哈希密碼加鹽

current_password = random hashed password(which must match the one stored in db). 

if(current_password == $db_password){ 

    enter new password 

} 

由於密碼總是隨機的,因此上述條件不會成立。

我的功能

function cryptPass($input,$rounds = 9) { 
    $salt = ""; 
    $saltChars = array_merge(range('A','Z'),range('a','z'),range(0,9)); 
    for($i = 0;$i < 22; $i++){ 
     $salt .= $saltChars[array_rand($saltChars)]; 
    } 
    return crypt($input,sprintf('$2y$%02d$', $rounds).$salt); 
} 
$pass = "password"; 
$hashedPass = cryptPass($pass); 

echo $hashedPass; 

i have 3 column in my user table (id, username, password). 

任何一個可以告訴我如何正確使用此功能, 還是有做這一個最好的方法?

+1

商店與密碼一起在食鹽。 –

回答

0

你需要做同樣的步驟,你會爲登錄。檢查輸入的舊密碼是否與數據庫中的密碼哈希匹配,然後根據輸入的新密碼創建哈希並存儲它。

PHP已經有一個函數password_hash()來創建一個散列函數和一個函數password_verify()來檢查輸入的密碼是否與存儲的密碼哈希匹配。

// 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); 

所以您的代碼會是這個樣子:

​​
+0

是在php 5.5之前的php版本中可用的password_hash()嗎? – dxcoder1

+0

@ dxcoder1 - 對於早期的PHP版本,有[兼容包](https://github.com/ircmaxell/password_compat/blob/master/lib/password.php)。因此,您可以使用相同的「未來證明」功能(稍後您可以刪除兼容包)。即使對於5.3.7之前的PHP有一個可能性,看看這個[答](http://stackoverflow.com/a/22260436/575765)。 – martinstoeckli

0

您想要存儲數據庫中生成的$salt以及散列密碼。然後,當你來檢查密碼時,你將能夠從數據庫中獲取鹽並再次用於哈希過程。

因此,與您的數據庫表有它的一個額外的列被稱爲「鹽」

(id, username, password, salt) 
+0

謝謝,這應該做到這一點。 – dxcoder1

+0

這不是問題,因爲crypt()函數在生成的哈希值中包含salt,並且爲了驗證,它會自動從存儲的哈希值中提取salt。 – martinstoeckli