Hashing

Introduction

The Laravel Hash facade provides secure Bcrypt and Argon2 hashing for storing user passwords. If you are using the built-in LoginController and RegisterController classes that are included with your Laravel application, they will use Bcrypt for registration and authentication by default.

{tip} Bcrypt is a great choice for hashing passwords because its "work factor" is adjustable, which means that the time it takes to generate a hash can be increased as hardware power increases.

Configuration

The default hashing driver for your application is configured in the config/hashing.php configuration file. There are currently three supported drivers: Bcrypt and Argon2 (Argon2i and Argon2id variants).

{note} The Argon2i driver requires PHP 7.2.0 or greater and the Argon2id driver requires PHP 7.3.0 or greater.

Basic Usage

You may hash a password by calling the make method on the Hash facade:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Hash;
  5. use App\Http\Controllers\Controller;
  6. class UpdatePasswordController extends Controller
  7. {
  8. /**
  9. * Update the password for the user.
  10. *
  11. * @param Request $request
  12. * @return Response
  13. */
  14. public function update(Request $request)
  15. {
  16. // Validate the new password length...
  17. $request->user()->fill([
  18. 'password' => Hash::make($request->newPassword)
  19. ])->save();
  20. }
  21. }

Adjusting The Bcrypt Work Factor

If you are using the Bcrypt algorithm, the make method allows you to manage the work factor of the algorithm using the rounds option; however, the default is acceptable for most applications:

  1. $hashed = Hash::make('password', [
  2. 'rounds' => 12
  3. ]);

Adjusting The Argon2 Work Factor

If you are using the Argon2 algorithm, the make method allows you to manage the work factor of the algorithm using the memory, time, and threads options; however, the defaults are acceptable for most applications:

  1. $hashed = Hash::make('password', [
  2. 'memory' => 1024,
  3. 'time' => 2,
  4. 'threads' => 2,
  5. ]);

{tip} For more information on these options, check out the official PHP documentation.

Verifying A Password Against A Hash

The check method allows you to verify that a given plain-text string corresponds to a given hash. However, if you are using the LoginController included with Laravel, you will probably not need to use this directly, as this controller automatically calls this method:

  1. if (Hash::check('plain-text', $hashedPassword)) {
  2. // The passwords match...
  3. }

Checking If A Password Needs To Be Rehashed

The needsRehash function allows you to determine if the work factor used by the hasher has changed since the password was hashed:

  1. if (Hash::needsRehash($hashed)) {
  2. $hashed = Hash::make('plain-text');
  3. }