Password hashing and verification using PHP's password_hash function
P粉798010441
P粉798010441 2023-10-13 23:55:11
0
2
447

Lately I've been trying to implement my own security on a login script I stumbled across on the internet. After struggling to learn how to make my own script to generate a salt for each user, I stumbled upon password_hash.

From what I understand (based on reading this page), when you use password_hash the salt is already generated on the line. This is real?

My other question is, wouldn't it be wise to have 2 types of salt? One directly in the file and one in the database? This way, if someone corrupts the salt in the database, you can still save the salt directly in the file? I read here that storing salt is never a smart idea, but it always confuses me what people mean by that.

P粉798010441
P粉798010441

reply all(2)
P粉520545753

Yes, you understand correctly, the function password_hash() will generate the salt by itself and include it in the generated hash value. It is absolutely correct to store the salt in the database, even if it is known to do its job.

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);

// 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($_POST['password'], $existingHashFromDb);

The second salt you mentioned (the one stored in the file) is actually the pepper or server side key. If you add it before hashing (just like salt), then you're adding pepper. There is a better way though, you can first calculate the hash and then encrypt (both ways) the hash using a server side key. This allows you to change the key if necessary.

Contrary to the salt, this key should be kept secret. People often mix it up and try to hide the salt, but it's better to let the salt do its job and add the secret with the key.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!