Converting md5 password hashes to PHP 5.5 password_hash()

后端 未结 3 1377
情深已故
情深已故 2020-12-05 11:52

The new password_hash API in PHP 5.5 is nice and I\'d like to start using it everywhere. Given an older project with an older database where passwords are stored in md5 hash

3条回答
  •  误落风尘
    2020-12-05 12:38

    In your login.php (?) you convert the old passwords from MD5 to bcrypt and replace the old MD5 hash in the database with the new one.

    Pseudo code:

    $password = $_POST["password"];
    
    if (substr($pwInDatabase, 0, 1) == "$")
    {
        // Password already converted, verify using password_verify
    }
    else
    {
        // User still using the old MD5, update it!
    
        if (md5($password) == $pwInDatabase)
        {
            $db->storePw(password_hash($password));
        }
    }
    

    Double hashing would not increase the security of bcrypt, as bcrypt itsef is a one-way hashing function.

    Nota: MD5 produces a 32 character length string, while password_hash() is a minimum of 60.

    Read the manual:

    • http://php.net/manual/en/function.password-hash.php

    If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.

    You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.

提交回复
热议问题