Salting and hashing: In PHP, saving a password using salting and hashing is done with the password_hash() method. This method takes three parameters and returns the final hash of this password.
Syntax:string password_hash (string $pass, int $algo, array $options)
Parameters : - $pass: This parameter contains the password that must be protected and stored in the database.
- $algo: defines the hashing algorithm, which is used to create the $pass hash. Some of the algorithm options in php are:
- PASSWORD_DEFAULT: use bcrypt algorithm (default in PHP 5.5.0). This constant is intended to change over time as new and stronger algorithms are added to PHP.
- PASSWORD_BCRYPT: This is the CRYPT_BLOWFISH algorithm for generating the hash. Result on a 60 character string, or FALSE on error.
- $options: salted part. Requires salt in a cost form factor. Optionally, if left blank, a default value is added to the string (in most cases it is 10). Note that a higher cost leads to a more secure password and thus increases CPU utilization.
Return Value: Returns a hashed password and FALSE on error .
Example: This example demonstrates reading password_hash(), generating a hash, and comparing it.
// Save the string to a variable
$password
=
’Password’
;
// Use the password_hash() function for
// generate password hash
$hash_default_salt
= password_hash (
$password
,
PASSWORD_DEFAULT);
$hash_variable_salt
= password_hash (
$password
,
PASSWORD_DEFAULT,
array
(
’cost’
= > 9));
// Use the password_verify() function for
// check if the password matches
echo
password_verify (
’Password’
,
$hash_default_salt
).
"
"
;
echo
password_verify (
’ Password’
,
$hash_variable_salt
).
"
"
;
echo
password_verify (
’ Password123’
,
$hash_default_salt
);
?>
Output: 1 1 0
This example uses the password_verify() method to compare the generated hash with the string entered as a parameter. It takes a hash and a comparison string as parameters and returns true if the password is correct, otherwise it returns false.