問題描述
我目前正在實施登錄系統(tǒng).我想將密碼和鹽存儲在數(shù)據(jù)庫中.現(xiàn)在我發(fā)現(xiàn)有一個 hash()
和一個 crypt()
函數(shù)似乎做了同樣的事情(對 SHA512 有效).
I'm currently implementing a login system. I want to store the password and the salt in a database. Now I found out that there is a hash()
and a crypt()
function which seems to do the same (valid for SHA512).
hash()
更新,似乎比 crypt()
支持更多的散列算法.或者我應該知道/關心其他任何差異嗎?
hash()
is newer and seems to support more hashing alogrithms than crypt()
. Or there any other differences I should know/care about?
function generatePasswordHash($password){
$salt = base64_encode(mcrypt_create_iv(8));
$calculatedPasswordHash = crypt($password, '$1$' . $salt . '$');
return $calculatedPasswordHash;
}
結果看起來像 $1$Qh6ByGJ9$zLn3yq62egvmc9D7SzA2u.
這里是我的密碼檢查功能:
Here my password checking function:
function checkLoginData($username, $password){
global $db;
$sql = "SELECT * FROM users WHERE username = :username";
$result = $db->ExecuteQuery($sql, array("username"=>$username));
if(!empty($result)){
$result = $result[0];
$savedPasswordHash = $result['password'];
$splitted = explode("$", $savedPasswordHash);
$salt = $splitted[2];
$calculatedPasswordHash = crypt($password, '$1$' . $salt . '$');
if($savedPasswordHash === $calculatedPasswordHash){
return true;
}
}
return false;
}
推薦答案
使用 hash
進行散列,例如在完整性檢查中.直接使用指定的哈希算法.
Use hash
for hashing, for example in integrity checks. It directly uses the specified hashing algorithm.
crypt
是一個特殊用途的函數(shù).它用于密碼散列和密鑰派生.您需要傳入一個鹽,它間接確定了所使用的散列方案.即使您選擇 CRYPT_SHA512
,這也不是普通的 SHA512.這是一個使用 SHA512 作為構建塊的密鑰派生函數(shù).特別是這種方案是故意緩慢的(隱藏暴力攻擊)并且以安全的方式結合了鹽和密碼.
crypt
is a special purpose function. It's used for password hashing and key derivation. You'll need to pass in a salt, which indirectly determines the hashing scheme used. Even if you choose CRYPT_SHA512
this isn't plain SHA512. It's a key derivation function that uses SHA512 as building block. In particular such a scheme is deliberately slow(hider brute-force attacks) and combines salt and password in a secure way.
對于日志系統(tǒng)中的密碼散列,crypt
顯然是正確的選擇.
For password hashing in a log system, crypt
is clearly the right choice.
這篇關于hash() 與 crypt() 函數(shù)比較的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!