Skip to content

Hashing

Giới thiệu (Introduction)

Hash facade cung cấp Bcrypt và Argon2 hashing an toàn để lưu trữ mật khẩu users. Nếu dùng Starter Kits, Bcrypt sẽ được dùng mặc định cho registration và authentication.

Tại sao Bcrypt? Bcrypt là lựa chọn tuyệt vời vì "work factor" có thể điều chỉnh — thời gian tạo hash tăng theo sức mạnh hardware. Khi hash passwords, chậm là tốt — thuật toán càng chậm, attacker càng khó tạo "rainbow tables".

Cấu hình (Configuration)

Mặc định driver bcrypt. Các drivers khác: argon, argon2id.

env
HASH_DRIVER=bcrypt

Publish cấu hình hashing:

bash
php artisan config:publish hashing

Sử dụng cơ bản (Basic Usage)

Hash Passwords

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;

class PasswordController extends Controller
{
    public function update(Request $request): RedirectResponse
    {
        $request->validate([
            'password' => ['required', 'confirmed', 'min:8'],
        ]);

        $request->user()->fill([
            'password' => Hash::make($request->password),
        ])->save();

        return redirect('/profile');
    }
}

Điều chỉnh Bcrypt Work Factor

php
$hashed = Hash::make('password', [
    'rounds' => 12,
]);

Điều chỉnh Argon2 Options

php
$hashed = Hash::make('password', [
    'memory' => 1024,
    'time' => 2,
    'threads' => 2,
]);

Xác minh Password khớp Hash

php
if (Hash::check('plain-text', $hashedPassword)) {
    // Password khớp...
}

Kiểm tra cần Rehash

Kiểm tra xem hash có cần cập nhật (ví dụ: work factor đã thay đổi):

php
if (Hash::needsRehash($hashed)) {
    $hashed = Hash::make('plain-text');
}

Hash Algorithm Verification

Để ngăn hash algorithm manipulation, bạn có thể verify hash algorithm:

php
// Trong AppServiceProvider::boot()
use Illuminate\Support\Facades\Hash;

Hash::verifyAlgorithm(true);

Khi bật, nếu hash value sử dụng algorithm khác với configured driver, exception sẽ được throw khi verify — ngăn attacker downgrade algorithm.