We are putting lots of effort and logic to save password securely in database. Most of web developers are still using less secure and old algorithm like SHA1 and MD5 encryption etc. But these password are in plain string and can be easily cracked.
PHP5.5 release new functions for password management, which we are going to cover in this tutorial. The new password hashing API uses bcrypt means it’s a key derivation function for passwords.
There are 4 password hashing functions were introduced into PHP5.5
- password_hash – used to hash the password
- password_verify – Verifies that a password matches a hash
- password_get_info – Returns information about the given hash
- password_needs_rehash – Checks if the given hash matches the given options
Login script demo with password hashing – PHP Login Script using PDO
The two important functions to understand are the password_hash() and the password_verify().
$password = "StepBlogging";
$hash = password_hash($passwod, PASSWORD_DEFAULT);
// output - $2y$10$sm5bCxR9cqLizW1ur.NLbep4SnnUMthNRgHTeKlw5Gpqom3v3GuEe
In this function the first parameter is password and second parameter used to specify the algorithm to hash password.
PASSWORD_DEFAULT – is the bcrypt algorithm (default as of PHP 5.5.0).
If you want to give your own salt then there is an options to add it as a third parameter in it.
$params = [
'salt' => generate_salt(), // write your own code to generate a salt
'cost' => 11 // allows for you to change the CPU cost of the algorithm
echo password_hash($password, PASSWORD_DEFAULT, $params );
The outputted string will always begin with a dollar ($) symbol, followed by 2y (meaning Blowfish), another $, the number of times the password is re-hashed (cost) and finally the hashed password. [$2y$10$sm5bCxR9cqLizW1ur.NLbep4SnnUMthNRgHTeKlw5Gpqom3v3GuEe]
For checking passwords, we can use password_verify function, which checks a password string against a password hash, then returns a boolean.
$toCheck = 'StepBlogging';
$isValid = password_verify($toCheck, '$2y$10$sm5bCxR9cqLizW1ur.NLbep4SnnUMthNRgHTeKlw5Gpqom3v3GuEe');
//ouput - $isValid == true