AppDividend
Latest Code Tutorials

PHP Password Hashing Functions API Example

0

PHP Password Hashing Functions API Example is today’s topic. The new hashing functions API in PHP 5.5 provides support towards bcrypt while hiding its complexity. You should be hashing the users’ passwords using the bcrypt() function, but still, a surprising number of developers uses the insecure md5() or sha1() hashes (look at the recent password leaks).

PHP Password Hashing Functions

Are you hashing your user passwords? If not, you’re asking for trouble. Keeping the plain text passwords or using older, weaker algorithms like MD5 or SHA1 to store passwords have become outdated practice and less secure than newer, modern methods. For example, with the release of PHP 5.5, you can use the password hashing api.

By adding the new, very simple to use API PHP hopes to move more developers towards bcrypt. It has four simple functions:

  1. password_get_info — It returns information about the given hash.
  2. password_hash — It creates a password hash.
  3. password_needs_rehash — It checks if the given hash matches the given options.
  4. password_verify — It verifies that a password matches a hash.

password_hash() in PHP

When you need to hash the password, pass the password string to a function and it will return a hash which you can save in your database.

See the following code.

<?php

// app.php
  
$pwd = 'Starboy';
$hashpwd = password_hash($pwd, PASSWORD_BCRYPT);
echo $hashpwd;

Here, in the password_hash() function, we have passed two parameters.

  1. $pwd
  2. PASSWORD_BCRYPT

The default algorithm is currently bcrypt, but the stronger algorithm may be added as a default later at any point in the future may generate the larger string.

If you are using the PASSWORD_DEFAULT in your projects, be sure to save the hash in the column that’s capacity is beyond 60 characters. So set the SQL Datatypes according to it.

Setting a column size to 255 might be the good choice. You can use the PASSWORD_BCRYPT as a second parameter.  In this case, the output will always be the 60 characters long.

See the output.

➜  pro php app.php
$2y$10$YkCr7mbJ6Fh8osXvbes/rud4ZfykHWWFUH.h2BK.HMY5FXi1R9Hby                    
➜  pro

Let’s use PASSWORD_DEFAULT as a second parameter.

<?php

// app.php
  
$pwd = 'Starboy';
$hashpwd = password_hash($pwd, PASSWORD_DEFAULT);
echo $hashpwd;

See the output.

➜  pro php app.php
$2y$10$2dl7qSkh4zExF6xeR5eE.uhFM4Ym3dvKv00oRCx/fGlVQR9ny1FkS                   
➜  pro

This will create the password hash using the default algorithm (currently bcrypt), the default load factor (now 10) and the automatically created salt.

The used algorithm and salt will also be a part of the resulting hash, so you don’t need to worry about them.

One crucial thing here is that you don’t have to provide the salt value or the cost parameter.  The new hashing API will take care of all of that for you.

The salt is the part of a hash, so you don’t have to save it separately.

If you want to provide your salt (or cost), you can do so by passing the third argument to a function, the array of options.

Verifying Hashed Password using password_verify()

Remember that you save the hashes in the database, but it’s the plain password that you get when a user logs in.

The password_verify() function takes the plain password and a hashed string as its two arguments. It returns true value if the hash matches a specified password.

Verifying passwords is just as easy. See the following code.

<?php

// $password from user, $hash from database

if (password_verify($password, $hash)) {
    // password valid!

} else {
    // wrong password :(
}

Just remember that the salt is the part of the hashed password which is why we are not specifying it separately here.

Rehashing Pwd using password_needs_rehash

In future, you might want to change a password hashing the algorithm or load factor, or PHP may change the default settings to be more secure algorithm.

In this case, the new accounts should be generated using the latest options and the existing passwords rehashed on login (you can do this only on the login because you need an original password to do the rehash).

password_needs_rehash ( string $hash , int $algorithm [, array $options ] ) : bool

hash

A hash created by password_hash().

algorithm

The password algorithm constant denoting the algorithm to use when hashing the password.

options

The associative array containing all the options. See a password algorithm constants for the documentation on the supported options for each algorithm.

The password_needs_rehash() function checks to see if a supplied hash implements an algorithm and options provided. If not, then it is assumed that the hash needs to be rehashed.

See the code.

<?php
if (password_needs_rehash($hash, PASSWORD_DEFAULT, ['cost' => 12])) {
    // the password needs to be rehashed as it was not generated with
    // the current default algorithm or not created with the cost
    // parameter 12
    $hash = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);

    // don't forget to store the new hash!
}

Retrieve PHP Hashed Password Info

The password_get_info() returns information about the given hash. It accepts the hash and returns an associative array of three elements.

  1. algo: A constant that identifies a particular algorithm.
  2. algoName: The name of the algorithm used.
  3. options: Various options used while generating the hash.

See the following syntax.

password_get_info (string $hash)

The $hash is created by an algorithm supported by password_hash(). The password_hash() function will return an array of information about that hash.

See the following code.

<?php

// app.php
  
$pwd = 'Starboy';
$hashpwd = password_hash($pwd, PASSWORD_DEFAULT, ['cost' => 11]);
echo 'Hash of the Password: ', $hashpwd;

print_r(password_get_info($hashpwd));

See the output.

➜  pro php app.php
Hash of the Password: $2y$11$Xxv04ESL.Q.30wE9n6I9.OFJh.KiH9/HNN2LeUOf0QRot6s/4HqliArray
(
    [algo] => 1
    [algoName] => bcrypt
    [options] => Array
        (
            [cost] => 11
        )

)
➜  pro

Compatibility for Older PHP Versions

The new hashing API will only be introduced in the PHP version 5.5. For those who are currently using PHP 5.3.7 (or older version) can use the library called password_compat which emulates that API and automatically disables itself once the PHP version is upgraded to 5.5.

Finally, PHP Password Hashing Functions API Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.