search
HomeBackend DevelopmentPHP TutorialLaravel Password Hashing With Salt

Recently we went deep into the Laravel authentication system for some improvements and to add Multi-Factor authentication. I discovered some interesting details on how Laravel password hashing works.

This article can help you understand how secure your application is from this point of view or if it is necessary to make some changes in your PHP app to increase security.

Spoiler: Despite the title of the article, Laravel doesn't use a salt to hash your user's password, PHP does.

You can follow me on Linkedin or X. I post about building my SaaS product.

Hashing is different from Encryption

To avoid any misunderstanding, let me clarify that Hashing and Encryption are two very different things. Hashing is one way. Starting from a hash you cannot get back to the original string. Encryption instead is two ways. You can encrypt and decrypt strings.In fact these two features are provided through two different Laravel Facades: Illuminate\Support\Facades\Hash (for hashing), Illuminate\Support\Facades\Crypt (for encryption).

Laravel Password Hashing With Salt

In the case of passwords, we want to store the hash so even in case of a data breach there is no way to get back the original password so the user credentials still protected.

How does Laravel make the password hash?

Obviously with the make method on the Hash service:

\Illuminate\Support\Facades\Hash::make(‘password’);

// Output
$2y$10$PeZ29z5axgJUZiy01tMBMuQuego6WLCDUV34LJbVowg4AKcZFl4mC

If you run this instruction multiple times you will get a different result each time:

$2y$10$PeZ29z5axgJUZiy01tMBMuQuego6WLCDUV34LJbVowg4AKcZFl4mC
$2y$10$cYoHztp3QwzRvdTmzEE5xeXfXjbc6Ix3C9LhBungA/DIHcBLtgAE2
$2y$10$Mz30EAiaHtZZ1J5m6yrVbuHJcZr4r4iV.RYGX8I.pZ9tT2wThGPKW

So, How the hell does Laravel compare two passwords to check if they are the same? It's the check we need to do when a user is logging in.

The counter part of the make() method is check():

use Illuminate\Support\Facades\Hash;

// Stored hashed password retrieved from the database
$storedHash = '$2y$10$Oi4mNb5kKDWtVzbs6fLCie.Uy1eG1n0BnDO1QazrF8b1/LJZVWJSO';

// User-provided password during login attempt
$userInputPassword = 'password';

// Verify if the user-provided password matches the stored hash
if (Hash::check($userInputPassword, $storedHash)) {
    echo "Password verified!";
} else {
    echo "Invalid password!";
}

Laravel Password Hashing is a wrapper of PHP password functions
The Laravel password hashing component is an abstraction to use two native PHP functions with a predefined setup: password_hash, and password_verify. Both are a native wrappers of the low level crypt function.

This are the internal implementation of the two methods in the Laravel BcryptHasher:

Hash::make($password);

public function make($value, array $options = [])
{
    $hash = password_hash($value, PASSWORD_BCRYPT, [
        'cost' => $this->cost($options),
    ]);

    if ($hash === false) {
        throw new RuntimeException('Bcrypt hashing not supported.');
    }

    return $hash;
}
Hash::check($password, $storedHash);

public function check($value, $hashedValue, array $options = [])
{
    if (is_null($hashedValue) || strlen($hashedValue) === 0) {
        return false;
    }

    return password_verify($value, $hashedValue);
}

As mentioned in the PHP documentation:

password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

In the examples above I reported some results of the Hash::make() that are the result of the password_hash() function eventually. You can notice the same pattern at the beginning of the string. It's a composition of the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

Internally, the password_verify() function works by performing the following steps:

Extracting Parameters: It extracts the parameters stored within the hash string itself. These parameters include the hashing algorithm, the cost, and the salt.

Hashing the Input Password: Using the extracted parameters, password_verify() rehashes the user-provided password using the same algorithm, salt, and cost factor that were used to generate the stored hash.

Comparison: After rehashing the input password, it compares the resulting hash with the stored hash. If the two hashes match, the input password is correct.

Here is an example of how the password_verify() function can be implemented in plain PHP so you can understand the process:

function password_verify($userInputPassword, $storedHash) {
    // Extract parameters from the stored hash
    $params = explode('$', $storedHash);
    $algorithm = $params[1];
    $cost = (int)$params[2];
    $salt = $params[3];

    // Rehash the user input password using the extracted parameters
    $rehashedPassword = crypt($userInputPassword, '$' . $algorithm . '$' . $cost . '$' . $salt);

    // Compare the rehashed password with the stored hash
    if ($rehashedPassword === $storedHash) {
        return true;
    } else {
        return false;
    }
}

Security considerations

password_hash() already generates a strong hash with a salt. From the Laravel configuration you can eventually change the cost factor through the bcrypt.rounds parameter in the config/hashing.php file.

/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/

'bcrypt' => [
    'rounds' => env('BCRYPT_ROUNDS', 10),
],

Increasing the cost factor (number of rounds) in the Bcrypt algorithm generally improves the security of passwords by making password hashing more computationally intensive and resistant to brute-force attacks.

For example the default value of the rounds parameter is 10, I use 12 in my application to strengthen my passwords a bit.

Monitor your PHP application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the composer package and you are ready to go.

Inspector is super easy and PHP friendly. You can try our Laravel or Symfony package.

If you are looking for HTTP monitoring, database query insights, and the ability to forward alerts and notifications into your preferred messaging environment, try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Laravel Password Hashing With Salt

The above is the detailed content of Laravel Password Hashing With Salt. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version