Laravel - How do you use Hash::needsRehash()? Laravel - How do you use Hash::needsRehash()? laravel laravel

Laravel - How do you use Hash::needsRehash()?


Hash::needsReHash() just calls php's built-in password_needs_rehash function. A helpful comment in the docs is:

// Check if a newer hashing algorithm is available// or the cost has changedif (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {

So Hash::needsReHash() will return false if and only if hashing algorithm has changed (since you're not passing any options such as cost).

As for how and when to use this, you can only rehash a user's password when you have it -- e.g. when they're logging in. So during the login process, you check if their stored password's algorithm differs from your current algorithm, and if so, you replace their stored password hash with a new one.


This seems to be how to do it in Laravel 5.6

Put this in your LoginController:

protected function authenticated(Request $request, $user) {    if (Hash::needsRehash($user->password)) {        $user->password = Hash::make($request->password);        $user->save();    }}

https://laravel.com/docs/5.6/hashing#basic-usage


The method returns true when PHP is updated and a new/better default algorithm was added or any other parameters changed. This lets you automatically take advantage of it without updating your code.

This method is used when a user is logging in as that is the only time you have access to the plain-text password. After confirming it is correct according to the old hash, you take the plain text password, rehash it, and put it back into the database for future use.

For a hypothetical example, lets say that right now the algorithm is md5() 10k times. In PHP7, it was updated to sha512() 15k times. If the hash is in the $count|$algo|$hash format, the method can tell when a hash is outdated. Since the old algorithm was not removed, you can still validate the password with old parameters before rehashing.

Note: obviously using md5()/sha512() is a bad idea. I'm just using them as examples.