PHP | Password hashing

Author - Deepika
1.02.2017
|
0 Comments
|

Password hashing is the new recommended way to store the password using hashing method (PHP 5 >= PHP 5.5, PHP7). Password hashing is used to encrypt the password similar to the way md5, sha1, sha256 etc do. But this method follows stronger hashing algorithm comparatively. There are two methods that are used in password hashing:

password_hash()
password_verify()

Password_hash method can be used with

PASSWORD_DEFAULT: Password hashing includes default method in which different salts can be used to produce hashed password. Every time if you run this algorithm it will give you different output.

For Example:

<?php 
$optional=['cost'=>'10'];
echo password_hash("testing_password", PASSWORD_DEFAULT,$optional);
?>

Output:
1
This algorithm takes execution time based on cost parameter value. By default the value of cost is 10. Cost value of 1 and 2 are not good for creating password hash.

The time execution for the password_hash method is more than other algorithms.

For Example:

<?php
    $time_start_hashing = microtime(true);
    password_hash("testing_password", PASSWORD_DEFAULT,array('cost'=>10));
    $time_stop_hashing = microtime(true);
    $time_start_md5_hashing = microtime(true);
    md5("testing_password");
    $time_stop_md5_hashing = microtime(true);
    $time_start_sha1_hashing = microtime(true);
    sha1("testing_password");
    $time_stop_sha1_hashing = microtime(true);
    echo "Time of execution for<br>";
    echo "password_hash is : ".($time_stop_hashing-$time_start_hashing)."<br>";
    echo "md5 is :".($time_stop_md5_hashing-$time_start_md5_hashing)."<br>";
    echo "sha1 is :".($time_stop_sha1_hashing-$time_start_sha1_hashing)."<br>";
?>

Output:
Time of execution for
password_hash is : 0.059037923812866
md5 is :4.0531158447266E-6
sha1 is :4.0531158447266E-6

password_verify method is used to verify the entered password without converting into hashing. And while checking the password from database should be enclosed into single quotes if you use double quotes then it will make it as three variables.

With double quotes:

"$2y$10$4uyV7NTlUbh/Ai9PWF0B3OFKfM4rnpTWTIrp0Bu1h8wpuyBUWYjs6"

With single quotes:

'$2y$10$sgQD.1DhMj1PSk2iuKh6P.XR/HutLg5ueXbYP/7jtEuAWoe7H1CWC'

For Example:

<?php
$password_to_verify='$2y$10$p9GsNlS0VeLx844qlfF9MONyxYehPh0zJJJVHAOyN1kdz74D9658y';
if(password_verify("testing_password", $password_to_verify)){
echo "Password verified successfully";
}
else {
echo "Password not verified";
}
?>

Output:
Password verified successfully

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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