How to use PHP's password_hash function for password hashing and verification
P粉538462187
2023-08-21 18:37:28
<p>Lately I have been trying to implement my own security on a login script I found on the internet. While trying to learn how to generate a salt per user, I stumbled upon <code>password_hash</code>. </p>
<p>As far as I understand (from reading on this page), when using <code>password_hash</code>, the salt is already generated in the line. is this real? </p>
<p>I have another question, is it wise to use two salts? One directly in the file and one in the database? This way, if someone cracks the salt in the database, you still have that salt in the file. I've read here that storing salt is never a wise idea, but I've always been confused by what people mean by this. </p>
Yes, you understand correctly, the function password_hash() will automatically generate a salt and include it in the generated hash value. Storing the salt in the database is perfectly correct and will work even if it is known.
The second salt you mention (the one stored in the file) is actually a "pepper" or server side key. If you add it before the hash (like salt), then you're adding a kind of pepper. However, there is a better way, you can calculate the hash first and then encrypt (two-way encryption) the hash using a server-side key. 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 into database and files.Suppose we have the following input:
First hash the password by:
Then check the output:
You can see that it has been hashed (I assume you have completed these steps).
Now store this hashed password into the database, Make sure your password column is large enough to accommodate the hash value (at least 60 characters or longer) . When the user asks to log in, you can check if the hash in the database matches the password input via:
Official reference