2014-02-24 147 views
0

我正在嘗試註冊並登錄帶有鹽加密的表單,但我並不十分熟悉它。所以一切正常,除了登錄無法識別密碼,所以我很確定這是加密問題。這些線寄存器:PHP鹽加密/解密密碼

$hash = hash('sha256', $password1); 
function createSalt() 
{ 
$text = md5(uniqid(rand(), true)); 
return substr($text, 0, 3); 
} 
$salt = createSalt(); 
$password = hash('sha256', $salt . $hash); 

,這些都是對登錄:

$userData = mysql_fetch_array($result, MYSQL_ASSOC); 
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password)); 
if($hash != $userData['password']) 
{ 
echo "Incorrect password"; 
} 

任何人都可以點的問題。謝謝!

回答

0

這有很多不對的地方。 對於初學者:您是否用密碼存儲鹽?如果不是,則密碼變得無法驗證。

安全考慮:

hash('sha256', ...不足;考慮bcrypt,scrypt,或PBKDF2

$text = md5(uniqid(rand(), true));聽說過的openssl_random_pseudo_bytes()

(同樣,你不應該試圖解密密碼,只有驗證。)

如果你不熟悉這些概念,發揮它的安全,並使用一個嘗試和真正的圖書館。

2

其實你的代碼應該盡我所能地工作,雖然它是非常不安全的!

  1. 問題:SHA256不適合哈希密碼,因爲它太快了。使用像BCrypt這樣的慢鍵推導函數。
  2. 問題:三字母鹽只有字母幾乎沒有保護。

也許您的數據庫字段小於64個字符,或者您正在比較不同的密碼。在任何情況下,都有一種更簡單更安全的哈希密碼方式,只需使用新功能password_hash()password_verify()即可。早期的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);