2

I am looking to implement BCrypt into a web application, however I am left lost in how to incorporate / change the level of work / iterations/rounds:

php.net crypt function states

As of PHP 5.3.0, PHP contains its own implementation.

I understand that using $pw = crypt($password); will automatically create a random salt for me and that I can just store $pw in the database.

I understand that I can check the password validity using

if ( crypt($user_input, $pw) == $pw) ) {
    // password is valid
} else {
    // password is not valid
}

I am aware that the reason that Bcrypt is so good, is that bcrypt is an adaptive function based on the Blowfish crypt. over time, the number of rounds can be increased to make it slower, so it remains resistant to brute force attacks despite faster computing technology.

So my question is, how do I slow down or speed up the checking of validity of the password? Or in another way, how do I set default number of iterations required to create my hashed password?

Gravy
  • 12,264
  • 26
  • 124
  • 193
  • The `crypt()` function will _not_ generate a random salt for you. There is a new function for PHP 5.5 called [password_hash()](http://www.php.net/manual/en/function.password-hash.php) though, that will handle all the stuff with autmatically generating a safe salt. Internally it will call the crypt() function. Use `password_hash()` instead, there exists a [compatibility pack](https://github.com/ircmaxell/password_compat/blob/master/lib/password.php) for earlier PHP version too. – martinstoeckli Jul 01 '13 at 15:15

2 Answers2

2

Here's one solution:

https://github.com/ircmaxell/password_compat

Usage:

$options = array('cost' => 8); // 2^cost is the number of iterations 
$hash = password_hash("adsfasdf", PASSWORD_BCRYPT, $options);

See here for a more through answer:

Community
  • 1
  • 1
lollercoaster
  • 15,969
  • 35
  • 115
  • 173
1

It's all in the documentation. The salt value in this case must be

"$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail.

So for 1024 (2^10) rounds the call should be

crypt($user_input, "$2y$10$......................");

where each . represents one salt character from the legal alphabet. Increasing/decreasing the parameter 10 by one doubles/halves the number of rounds respectively.

Jon
  • 428,835
  • 81
  • 738
  • 806