How to verify that a password matches a hash

widget

Why do we hash passwords?

The primary reason to hash a password is for security purposes. If there is a breach in the database, the real password remains inaccessible.

Hashing encrypts the string sent to the database. With the use of the Hash façade that provides the BCRYPT, hashing makes the password look like jargon.

What is password hashing?

Essentially, password hashing scrambles a user’s plain text password to avoid storing plaintext in the database.

In this context, we use the BCRYPT and Argon2 algorithm that ships with the Hash facade.

Let’s dive in

Let’s say you want to create your own Login module.

You will need to verify the user passwords to see if they match the passwords stored in the database.

To do this, we call check() on the Hash façade. The check() method verifies if the plain-text string entered by the user matches the given hash.

We can do this like so:

if (Hash::check($request->('password'), $hashedPassword)) {
    // The passwords match...
    }

The code above uses the Hash facadeAs mentioned earlier, the Hash facade provides BCRYPT and Argon2 hashing alongside the check() method.

The check() method needs two arguments:

  1. The first argument receives the $request->('password') from the users.
  2. The second argument receives the $hashedPassword from the database that we want to check.

When we make the hash using the make() method, the $hashedPassword is the password retrieved from the database.

The check() method compares the retrieved password to the password passed from the request and returns a Boolean.

Free Resources