ホームページ バックエンド開発 PHPチュートリアル Laravel パスワードをソルトでハッシュする

Laravel パスワードをソルトでハッシュする

Sep 09, 2024 pm 04:31 PM

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.

HTTP モニタリング、データベース クエリの洞察、アラートや通知を好みのメッセージング環境に転送する機能をお探しの場合は、Inspector を無料でお試しください。アカウントを登録してください。

または、Web サイトで詳細をご覧ください: https://inspector.dev

Laravel Password Hashing With Salt

以上がLaravel パスワードをソルトでハッシュするの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PHP変数スコープは説明されています PHP変数スコープは説明されています Jul 17, 2025 am 04:16 AM

PHP変数スコープの一般的な問題とソリューションには次のものが含まれます。1。グローバル変数は関数内でアクセスできず、グローバルキーワードまたはパラメーターを使用して渡す必要があります。 2。静的変数は静的で宣言され、1回のみ初期化され、値は複数の呼び出し間で維持されます。 3. $ _GETや$ _POSTなどのハイパーグローバル変数は、任意の範囲で直接使用できますが、安全なフィルタリングに注意を払う必要があります。 4.匿名関数は、使用キーワードを使用して親スコープ変数を導入する必要があり、外部変数を変更する場合は、参照を渡す必要があります。これらのルールを習得すると、エラーを回避し、コードの安定性が向上するのに役立ちます。

PHPコメントを書くためのヒント PHPコメントを書くためのヒント Jul 18, 2025 am 04:51 AM

PHPコメントを書くための鍵は、目的と仕様を明確にすることです。コメントは、「何が行われたのか」ではなく「なぜ」を説明する必要があり、冗長性や単純さを避けてください。 1.読みやすさとツールの互換性を向上させるために、クラスおよびメソッドの説明にdocblock(/*/)などの統合形式を使用します。 2。JSジャンプを手動で出力する必要がある理由など、ロジックの背後にある理由を強調します。 3.複雑なコードの前に概要説明を追加し、手順でプロセスを説明し、全体的なアイデアを理解するのに役立ちます。 4. TodoとFixmeを合理的に使用して、To Doアイテムと問題をマークして、その後の追跡とコラボレーションを促進します。優れた注釈は、通信コストを削減し、コードメンテナンスの効率を向上させることができます。

PHPでコードをコメントします PHPでコードをコメントします Jul 18, 2025 am 04:57 AM

PHPコメントコードには3つの一般的な方法があります。1。//#を使用して1行のコードをブロックすると、//を使用することをお勧めします。 2。使用/.../複数の行でコードブロックをラップするには、ネストすることはできませんが交差することができます。 3. / if(){}を使用するなどの組み合わせスキルコメントロジックブロックを制御するか、エディターショートカットキーで効率を改善するには、シンボルを閉じることに注意を払い、使用時にネストを避ける必要があります。

クイックPHPインストールチュートリアル クイックPHPインストールチュートリアル Jul 18, 2025 am 04:52 AM

to installphpquickly、usexampponwindowsorhomebrewonmacos.1.onwindows、downloadandinstallxampp、selectcomponents、startapache、andplacefilesinhtdocs.2

PHPの学習:初心者向けガイド PHPの学習:初心者向けガイド Jul 18, 2025 am 04:54 AM

tolearnphpefctivially、startbysettingupalocalserverenvironmentusingtoolslikexamppandacodeeditorlikevscode.1)instalxamppforapa Che、mysql、andphp.2)useocodeeditorforsyntaxsupport.3)testyoursetup withasimplephpfile.next、Learnpbasicsincludingvariables、ech

PHPを使用してソーシャル共有機能を構築する方法PHP共有インターフェイス統合プラクティス PHPを使用してソーシャル共有機能を構築する方法PHP共有インターフェイス統合プラクティス Jul 25, 2025 pm 08:51 PM

PHPでソーシャル共有機能を構築するコア方法は、各プラットフォームの要件を満たす共有リンクを動的に生成することです。 1.最初に現在のページまたは指定されたURLおよび記事情報を取得します。 2。urlencodeを使用してパラメーターをエンコードします。 3.各プラットフォームのプロトコルに従って、共有リンクをスプライスおよび生成します。 4.ユーザーがクリックして共有できるように、フロントエンドにリンクを表示します。 5.ページ上のOGタグを動的に生成して、コンテンツディスプレイの共有を最適化します。 6. XSS攻撃を防ぐために、必ずユーザーの入力を逃がしてください。この方法は、複雑な認証を必要とせず、メンテナンスコストが低く、ほとんどのコンテンツ共有ニーズに適しています。

AIと組み合わせてPHPを使用してテキストエラー修正PHP構文検出と最適化を実現する方法 AIと組み合わせてPHPを使用してテキストエラー修正PHP構文検出と最適化を実現する方法 Jul 25, 2025 pm 08:57 PM

AIによるテキストエラーの修正と構文最適化を実現するには、次の手順に従う必要があります。1。Baidu、Tencent API、またはオープンソースNLPライブラリなどの適切なAIモデルまたはAPIを選択します。 2。PHPのカールまたはガズルを介してAPIを呼び出し、返品結果を処理します。 3.アプリケーションにエラー修正情報を表示し、ユーザーが採用するかどうかを選択できるようにします。 4.構文の検出とコードの最適化には、PHP-LとPHP_CODESNIFFERを使用します。 5.フィードバックを継続的に収集し、モデルまたはルールを更新して効果を改善します。 AIAPIを選択するときは、PHPの精度、応答速度、価格、サポートの評価に焦点を当てます。コードの最適化は、PSR仕様に従い、キャッシュを合理的に使用し、円形クエリを避け、定期的にコードを確認し、Xを使用する必要があります。

PHPはAIインテリジェント音声アシスタントPHP音声相互作用システムの構築を呼び出す PHPはAIインテリジェント音声アシスタントPHP音声相互作用システムの構築を呼び出す Jul 25, 2025 pm 08:45 PM

ユーザー音声入力がキャプチャされ、フロントエンドJavaScriptのMediareCorder APIを介してPHPバックエンドに送信されます。 2。PHPはオーディオを一時ファイルとして保存し、STTAPI(GoogleやBaiduの音声認識など)を呼び出してテキストに変換します。 3。PHPは、テキストをAIサービス(Openaigptなど)に送信して、インテリジェントな返信を取得します。 4。PHPは、TTSAPI(BaiduやGoogle Voice Synthesisなど)を呼び出して音声ファイルに返信します。 5。PHPは、音声ファイルをフロントエンドに戻し、相互作用を完了します。プロセス全体は、すべてのリンク間のシームレスな接続を確保するためにPHPによって支配されています。

See all articles