Create and verify password in PHP with new hashing functions

Previously, when creating a login system, I usually take users’ password input and md5 it and store in the database. Doing so seemed to be sufficient enough. However, no one can be sure that their system is not vulnerable to attacks. In the worst case when your site gets hacked, your database is stolen, using weak hashing algorithm on users’ passwords may enable hackers to easily decode such fields. Thus, since PHP 5.5, there are new functions available to help you create an verify password hash easily. Let’s learn what are they and how to use them.

Creating a password hash with password_hash

Creating a password hash in PHP > 5.5 is very simple.

$hash = password_hash('easy-password', PASSWORD_DEFAULT, ['cost' => 12]);

and if you echo the hash, you’ll see something similar to this:

echo "hash is: {$hash}";

If you run the script again (reload the browser in my case), you’ll get a new hash string (still same password input!):

This is quite strange for people who are familiar to md5. In md5, for one input, there is one output. In this case, one input generates multiple outputs. This makes the effort to create a dictionary to map easily-to-guess passwords and their hashes become worthless.

password_hash takes 3 parameters:

  1. The raw password. This is what the users enter along with their email/id to login to your application
  2. The hashing algorithms. There are a few of them you can find out here.
  3. Additional options. Additional options which most of the time consists of the cost option. In the example, I used cost = 12. Higher cost provides higher security but takes more time.

Verify the password with password_verify

To verify the validity of a password hash, we’ll use password_verify. Consider the case of user login, they will provide the raw password (without hashing). Our application will get the hash password in the database and verify if the raw password and the hash match.

If you used md5 before, the code may look like this:

if ( md5($raw_user_input) == $password_hash_in_database )
{
//ok to login
}

However, if you hash the password using password_hash, you’ll use password_verify to verify.

 

if (password_verify($raw_user_input, $password_hash_in_database )
{
//ok to login
}

For example, in my case:

$verified = password_verify('easy-password', '$2y$12$06uHkyogkUveLLLVIFhvsOFzpBrYkZ8XIegVdwj0RtE/zI/dzfHnq');

echo "verify is: {$verified}";

The output is:

You can see that the hash was successfully verified.

That’s what I learned today. This is a part of 7 days challenges to learn one topic every day. Thanks for reading

Leave a Comment

Your email address will not be published. Required fields are marked *