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.