How can I extract salt from bcrypt hash passwords in php?

My database contains bcrypt passwords, which means that the salt should be stored in the password field. I do not want to create a separate field for storing salt myself when it is not needed. However, when I want to compare the passwords that the user sends me to the passwords stored in the database, I need to hash the incoming password with the same salt. Question: What part of the stored hash is salt? I think I can just return the salt using simple substr ().

// password stored in database. $user->password_hash = password_hash($password, PASSWORD_BCRYPT, array('cost' => 13)); // password from form being compared to form password $form_password_hash = password_hash($data['form-password'], PASSWORD_BCRYPT, array('cost' => 13)); if($user->getPasswordHash() == $form_password_hash) { $user->setPassword($data['new-password']); return new Response("Your password has been changed"); } 
+4
source share
2 answers

You need to use the password_verify function. This function will analyze the hashed password string to find the salt and perform the calculation.

 if (password_verify($data['form-password'], $user->getPasswordHash())) { echo 'Password is correct'; } 
+10
source

Salt - the first 22 characters after the third $ in the hash:

 $2y$13$<this is the salt, 22 chars><this is the password hash> 

But you do not have to manually extract the salt to verify the password - use the password_verify function. It enters the password entered by the user as the first argument, and the full hash the second argument and correctly processes the salt.

+7
source

Source: https://habr.com/ru/post/1488381/


All Articles