Yes, you understand correctly, the function password_hash() will automatically generate a salt and include it in the generated hash value. It is perfectly correct to store the salt in the database, it will work even if it is known.
// 為在數(shù)據(jù)庫中存儲的新密碼生成哈希值。 // 該函數(shù)會自動生成一個密碼學(xué)安全的鹽。 $hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT); // 檢查輸入的登錄密碼的哈希值是否與存儲的哈希值匹配。 // 鹽和成本因素將從$existingHashFromDb中提取。 $isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);
The second salt you mentioned (the salt stored in the file), is actually a pepper or server side key. If you add it before the hash (like salt), then you've added a chili pepper. But there is a better way, you can calculate the hash value first and then encrypt the hash value using the server side key (two-way encryption). This way you can change the key if necessary.
Unlike the salt, this key should be kept secret. People often get confused and try to hide the salt, but it's better to let the salt do its thing and use the key to add the secret.
Using password_hash
is the recommended way to store passwords. Don't store them separately in database and files.
Suppose we have the following input:
$password = $_POST['password'];
First hash the password by:
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
Then check the output:
var_dump($hashed_password);
As you can see, it has been hashed. (I assume you have completed these steps).
Now store this hashed password in your database, Make sure your password column is large enough to accommodate the hash value (at least 60 characters or longer) . When a user requests a login, you can check that the hash in the database matches the password input via:
// 查詢數(shù)據(jù)庫獲取用戶名和密碼 // ... if(password_verify($password, $hashed_password)) { // 如果密碼輸入與數(shù)據(jù)庫中的哈希密碼匹配 // 做一些操作,你懂的... 登錄他們。 } // 否則,將他們重定向回登錄頁面。