Generating Password Hash In PHP 5.5 And Setting Cost Option Generating Password Hash In PHP 5.5 And Setting Cost Option php php

Generating Password Hash In PHP 5.5 And Setting Cost Option


The function password_hash() is just a wrapper around the function crypt(), and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.

The easiest way to use this function will be:

$hash = password_hash($password, PASSWORD_DEFAULT);

That means, the function will hash the password with BCrypt (algorithm 2y), generates a random salt, and uses the default cost (at the moment this is 10). These are good default values, particularly i would not generate the salt of your own, it is easy to make mistakes there.

Should you want to change the cost parameter, you can do it like that:

$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 11]);

Increasing the cost parameter by 1, doubles the needed time to calculate the hash value. The cost parameter is the logarithm (base-2) of the iteration count, that means:

$iterations = 2 ^ $cost;

Edit:

I missed the point, that you want to generate your own class. For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. You can either use this code directly, or look at the well crafted implementation. For PHP versions before 5.3.7 there is no support for crypt with 2y, the unicode aware BCrypt algorithm. You can instead use 2a, which is the best alternative for earlier PHP versions. I did an example with a lot of comments, maybe you want to have a look at it too.

P.S. The expressions "salt" and "cost factor" are used correctly in password_hash(), the crypt() function though, uses the word salt for all crypt parameters together, that's a bit misleading.


Disclaimer: this is with PHP 5.3.10, but it seems not really different from your description.

The cost applies to the cost of computation. When you increase the cost value, it takes longer to hash the password

function blowfish_salt($cost){    $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';    $salt = sprintf('$2y$%02d$', $cost);    for ($i = 0; $i < 22; ++$i)        $salt .= $chars[rand(0,63)];    return $salt;}$password = 'My perfect password';$cost = $argv[1];$salt = blowfish_salt($cost);$hash = crypt($password, $salt);

When I run this on my (old) machine as

php mycrypt.php 10

it returns immediately (~0.2 sec), whereas with

php mycrypt.php 16

it takes about 5.2 seconds.