Open In App

What is the most used method for hashing passwords in PHP ?

Hashing password is a technique of converting a single password into another string called hashed password. The hashed password is generally one-way, i.e. we can’t go to the original password from the hashed password. So the thing is why we needed to use hashing to do all this stuff, why going one more mile if we can save our passwords into the database as a simple string. The one and only reason for doing all these is to enhance security because the hackers don’t steal credentials from our valuable site. So that’s why we use various hashing methods to hash passwords to secure our passwords while creating websites and storing our database. In PHP, there are various cryptographic algorithms that are commonly used like md5, crypt, sha1, and bcrypt. And the most commonly used nowadays is bcrypt hashing method. In this article, we are going to learn about bcrypt hashing method in PHP.

PHP provides a general password hashing function for creating a new password hash from the password.



Syntax:

string password_hash(string $password, string $algo, array $options = [])

Here, the password_hash function takes mainly three parameters that are:



Return Value: It returns a hashed password string.

Example:




<?php
 
$password = "GeeksforGeeks";
echo "Password is:", $password;
 
echo "Hashed password using CRYPT_BLOWFISH: ",
    password_hash($password, PASSWORD_BCRYPT);
echo "\n";
 
echo "Hashed password using Argon2i: ",
    password_hash($password, PASSWORD_ARGON2I);
echo "\n";
 
echo "Hashed password using bcrypt: ",
    password_hash($password, PASSWORD_DEFAULT);
?>

Output:

Password is: GeeksforGeeks

Hashed password using CRYPT_BLOWFISH: $2y$10$V4Cvy4caGAQBLWbw8i/PHOK9lopTYoxyQze3aZ3ocw9dDvju7Wxoi

Hashed password using Argon2i: $argon2i$v=19$m=65536,t=4,p=1$Y2F2TVouVWplYVYucy9DSw$p164c28N85L5v1i8GISN1oao10ZzNm9e/JAyicRaX/w

Hashed password using bcrypt: $2y$10$MQU3vDgoN10.JxyJ1m9UQOEqFy.Jg3D8tmHdZUAAkcpGFRwkbbLfi

Note: We have not used PASSWORD_ARGON2ID because it is not available in standard PHP installation.

To verify the hashed password: PHP provides an inbuilt function called password_verify to match the hashed password to the original passwords.

Syntax:

bool password_verify(string $password, string $hash)

Parameters:

Example:




<?php
 
$password = "GeeksforGeeks";
 
$hashed_password =
'$2y$10$MQU3vDgoN10.JxyJ1m9UQOEqFy.Jg3D8tmHdZUAAkcpGFRwkbbLfi';
 
echo "Original Password is: ", $password;
echo "\n";
 
echo "Hashed Password is: ", $hashed_password;
echo "\n";
 
if (password_verify($password, $hashed_password)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
 
?>

Output
Original Password is: GeeksforGeeks
Hashed Password is: $2y$10$MQU3vDgoN10.JxyJ1m9UQOEqFy.Jg3D8tmHdZUAAkcpGFRwkbbLfi
Password is valid!

Article Tags :