Password Hashing Function in PHP 5.5

As I mentioned before, one of the most welcoming new feature in PHP 5.5 is the new password hashing API. The API consists of four helper functions wrapped over the hard to use crypt function. Due to several password leaking incidents and most PHP developers still stick with plain MD5 or SHA512 hashing, there is a need for simple and stronger default password hashing API.

Imagine you have a existing user table with schema as shown below. The password field (pass) is a MD5 hashed field
- username varchar(255)
- password char(32)

First, to migrate from MD5 to BCRYPT hashing, we need to alter the password column to CHAR(60) BINARY or BINARY(60) if you're using MySQL. Why BINARY ? Space and speed reasons.

Second, rewrite your validation function so when user login to the system, if the record still using the old hashing method, validate it and update it using new hashing algorithm. Sample simplified code as follow:
function validate_login($username, $password)
{
    $password = get_user_password($username);
    if ( password_need_rehash($password, PASSWORD_BCRYPT) )
    {
        $valid = old_validate_login($username, $password);
        if ( ! $valid ) return FALSE;
        update_user_password($username,
            password_hash($password, PASSWORD_BCRYPT);
    }
    return password_hash($password, PASSWORD_BCRYPT) === $password;
}

How about those PHP version < 5.5 ? No worry, there exists a compatibility version which offers the similar functionality.

No comments:

Post a Comment