What is the best way to switch to the password_ * functions from the hash ('sha512', 'salt')

I really want to port my code to the new password_ * functions provided initially by PHP.

Existing hashes in the database were generated as follows:

hash ('sha512', '<A constant defined earlier>' . $email . $password);

I would like to move them to the hashes currently created:

password_hash ($password, PASSWORD_DEFAULT);

Obviously, when the user logs in, I can take the opportunity to create a new hash from the password just provided and save it in the database.

However, I would like for me not to have two fields in the database, namely for an obsolete hash and one for a modern password. Instead, I would rather replace the old ones as each user logs in.

Therefore, you can save one database field, and userland code determine whether the hash is old , i.e. determine which check to use?

(I assume that hash hashes ('sha512') cannot be automatically updated to crypt ()?)

+4
source share
2 answers

The hashes created with help password_hashwill have a very distinctive line $2y$at the beginning (or similar $..$if you are working with the current default Blowfish cypher ), and SHA256 will be just the sixth value. Therefore, you can simply check if the value is an obsolete hash value or a value password_hash:

function isLegacyHash($hash) {
    return !preg_match('/^\$\w{2}\$/', $hash);
}

, , . , hash_version.

+4

, . , . password_needs_rehash.

, , , .

, bcrypt - . , , .

true, , .

$password = 'test';
$oldHash = hash('sha512',); // get old Hash from DB
if (password_needs_rehash($oldHash, PASSWORD_BCRYPT)) {
    $newHash = password_hash($password , PASSWORD_BCRYPT);
    // save new Hash to DB (IMPORTANT: only if log in was successful...)
}
+2

All Articles