Current Location: Home> Latest Articles> How to Compare Two bcrypt Encrypted Passwords in Laravel

How to Compare Two bcrypt Encrypted Passwords in Laravel

gitbox 2025-06-12

1. Introduction

Laravel is a popular PHP web development framework. In Laravel development, password encryption is a common requirement because storing plain-text passwords can be insecure. Laravel provides a powerful and easy-to-use native password hashing algorithm, bcrypt. This article will explain how to compare two bcrypt encrypted passwords in Laravel.

2. bcrypt Hashing Algorithm

bcrypt is a password hashing algorithm based on the Blowfish encryption algorithm. It increases security by using salt and cost factors. The bcrypt algorithm concatenates the password with a salt, encrypts it using Blowfish, and outputs a hash of 60 characters in length. Below is an example of generating a bcrypt hash using PHP's password_hash()

3. Comparing Two bcrypt Hashes

In Laravel, you can easily compare plain-text passwords with bcrypt encrypted passwords using the Hash::check() method. The check() method compares the plain text password with the encrypted password, returning true if they match.

if (Hash::check('secret', $hashedPassword)) {
    // Returns true if the passwords match
}
    

Here, $hashedPassword is the bcrypt hash stored in the database.

3.1. Mnemonic

When using the check() method, make sure the first parameter is the plain text password, and the second parameter is the hashed password. You can remember the following mnemonic:

"With bpp, compare the pot": The first parameter is the plain text password (B), while the second parameter is the bcrypt hashed value (pp). In other words, the first parameter can be compromised, but the second is secure.

3.2. Example

Here is a complete example of comparing two bcrypt hash values:

$password = 'secret';
$hashedPassword = '$2y$10$LJrd9sGr0H1KSK8vVQVcMOZ0sQFpZ1t2qKZcKluXGDf9YOljxAF/6';

if (Hash::check($password, $hashedPassword)) {
    echo 'Password match successful!';
} else {
    echo 'Password match failed!';
}
    

Note: The check() method does more than just compare the two strings; it also verifies that the hash uses the correct encryption algorithm and has the proper format.