Which implementation of bcrypt is recommended for PHP 5.3?

前端 未结 2 460
名媛妹妹
名媛妹妹 2021-02-04 16:54

OK, I finally understand bcrypt, how it works, and how to store it in the DB, so I\'m almost good to go. The problem now is picking which implementation of bcrypt to use with P

2条回答
  •  清酒与你
    2021-02-04 17:17

    Best solution: you should use the password library that is being built-in for PHP 5.5. They've released a backward-compatibility version for PHP 5.3 and 5.4 called password_compat. However note that you'll need 5.3.7 or higher. There was a security issue with bcrypt prior to 5.3.7 which means that the new library won't work.

    If you are on a version prior to 5.3.7, then the next best option is Password Lib by the same author. But I'd suggest upgrading PHP instead would be the better option.

    Installing

    Both libraries can be installed simply by downloading them, copying them to your site folder, and including their main file in your code - ie require('password.php');.

    Installing via Composer is also an option if you are using it.

    Usage (Assuming you're going with password_compat):

    To create a password:

    $hash = password_hash($password, PASSWORD_BCRYPT);
    

    To verify a password:

    if (password_verify($password, $hash)) {
        /* Valid */
    } else {
        /* Invalid */
    }
    

    And that's basically all you need to know. The library handles all the other details for you like salting the password, etc.

    [EDIT] If you need to change the algorithm 'cost', as per your comment, then add an additional parameter to the password_hash() call to specify it, like this:

    password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
    

    Full documentation is available on the download page I linked above.

    The really good thing about using the password_compat library is that it is specifically designed to have the same API and functionality that is being built into PHP as standard in PHP 5.5. Therefore, if you use password_compat while you're on PHP 5.3 or 5.4, when you move to PHP 5.5 you'll already have the right code to in your system to use the new built-in password functions. The only difference will be that you won't need to include the library.

提交回复
热议问题