2014-10-08 52 views
-1

讓我們散列和鹽與密碼鹽醃:驗證密碼散列,並用password_hash

<?php 
$hash = password_hash('bonjour', PASSWORD_BCRYPT, ['cost' => 12, ]); 
// no salt option mentionned 
// then salt will be generated randomly, see password_hash documentation  
echo $hash; 
?> 

在頁面的每個重載結果的變化,這是正常的:是隨機生成的鹽,也可以是:

$2y$12$FlxBBjTjelKkGY.SJarlL.THUZBwcl7M6V35DmZmTmYJZRwhpRkIW 
$2y$12$p2pkD116hBHNc/2nyQ2WyOkrn.h8xvWvM1.Lmvsnhms2Y6zsb.j1e 
$2y$12$u4ipdQQM926jfanpXnwtkupv2CH/uWoPvK563tG7p.z35GcOBOZdS 
etc. 

在前面的代碼中,鹽似乎存儲在無處(我錯了嗎?)。但最後password_verify能夠檢查密碼與散列, 和它適用於每個結果,無論鹽是什麼。

<?php 
echo password_verify('bonjour', '$2y$12$FlxBBjTjelKkGY.SJarlL.THUZBwcl7M6V35DmZmTmYJZRwhpRkIW') ? 'yes' : 'no'; 
// yes 
echo password_verify('bonjour', '$2y$12$p2pkD116hBHNc/2nyQ2WyOkrn.h8xvWvM1.Lmvsnhms2Y6zsb.j1e') ? 'yes' : 'no'; 
// yes 
?>  

是不是正常的,password_verify能夠無需存儲salt地方檢查密碼?

回答

1

從PHP.net手冊

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

該鹽中的散列編碼,基本上。

+0

謝謝。所以將'password_hash()'(包含salt)的結果存儲在我的用戶名/密碼數據庫中是安全的嗎? – Basj 2014-10-08 11:35:23

+1

確實如此。這是它存在的主要原因之一。 – iamgory 2014-10-08 13:02:08