> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 建立自訂雜湊驅動

> 根據框架原始碼說明如何透過 HashManager 繼承的 Manager::extend() 註冊自訂雜湊驅動，並透過 Hash Facade 透明地使用它。

## 概要

`Hash` Facade 是 `Illuminate\Hashing\HashManager` 的代理。`HashManager` 是繼承 `Illuminate\Support\Manager` 的驅動管理器，預設提供 `bcrypt`、`argon` 與 `argon2id` 三種驅動。

官方文件只說明到透過 `HASH_DRIVER` 切換驅動，但由於 `HashManager` 直接沿用 `Manager` 的機制，因此可以加入自己的雜湊驅動。這裡以一個先將伺服器端的祕密金鑰（pepper）混入密碼、再用 bcrypt 儲存的驅動為例進行實作。

## 標準驅動的解析流程

呼叫 `Hash::make()` 時，會先呼叫 `Manager::driver()` 取得實際的驅動實例。

```php theme={null}
// Illuminate\Support\Manager::driver() 的簡化版
public function driver($driver = null)
{
    $driver = enum_value($driver) ?: enum_value($this->getDefaultDriver());

    return $this->drivers[$driver] ??= $this->createDriver($driver);
}
```

`createDriver()` 會先尋找已註冊的自訂建立器。找不到時，再尋找 `create{Name}Driver()` 方法。

```php theme={null}
// Illuminate\Support\Manager::createDriver() 的簡化版
protected function createDriver($driver)
{
    if (isset($this->customCreators[$driver])) {
        return $this->callCustomCreator($driver);
    }

    $method = 'create'.Str::studly($driver).'Driver';

    if (method_exists($this, $method)) {
        return $this->$method();
    }

    throw new InvalidArgumentException("Driver [$driver] not supported.");
}
```

`HashManager` 中有 `createBcryptDriver()`、`createArgonDriver()` 與 `createArgon2idDriver()`，分別回傳對應的雜湊器。若用 `extend()` 註冊相同名稱，自訂建立器會優先使用。

## 驅動的契約

雜湊驅動需實作 `Illuminate\Contracts\Hashing\Hasher` 介面。`HashManager` 的 `make()`、`check()` 等方法會將處理委派給透過 `driver()` 取得的目前驅動。

```php theme={null}
interface Hasher
{
    public function info($hashedValue);
    public function make($value, array $options = []);
    public function check($value, $hashedValue, array $options = []);
    public function needsRehash($hashedValue, array $options = []);
}
```

標準的 `BcryptHasher` 繼承 `AbstractHasher`。`AbstractHasher` 是包含 `info()` 與 `check()` 共通處理的基底類別。自訂驅動也使用相同的基底類別時，可以繼承 `check()` 中處理空雜湊等邏輯。

## 實作加入 pepper 的雜湊器

不是將密碼直接交給 bcrypt，而是先用 HMAC-SHA256 混入祕密金鑰，再交給 bcrypt。由於 bcrypt 只使用輸入的前 72 位元組，目的是先用 HMAC 將其轉為固定長度再傳入。

```php theme={null}
namespace App\Hashing;

use Illuminate\Hashing\AbstractHasher;
use Illuminate\Contracts\Hashing\Hasher;

class PepperHasher extends AbstractHasher implements Hasher
{
    public function __construct(
        protected string $pepper,
        protected int $rounds = 12,
    ) {}

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

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

        return password_verify($this->pepperize($value), $hashedValue);
    }

    public function needsRehash($hashedValue, array $options = [])
    {
        return password_needs_rehash($hashedValue, PASSWORD_BCRYPT, [
            'cost' => $this->cost($options),
        ]);
    }

    protected function pepperize(string $value): string
    {
        return hash_hmac('sha256', $value, $this->pepper);
    }

    protected function cost(array $options): int
    {
        return $options['rounds'] ?? $this->rounds;
    }
}
```

`check()` 中直接呼叫 `password_verify()`，是因為 `AbstractHasher::check()` 會直接驗證收到的明文。驗證必須使用套用 pepper 後的值，所以這裡加以覆寫。

## 註冊驅動

在 `AppServiceProvider` 的 `boot()` 方法中使用 `Hash::extend()` 註冊自訂驅動。

```php theme={null}
// app/Providers/AppServiceProvider.php
use App\Hashing\PepperHasher;
use Illuminate\Support\Facades\Hash;

public function boot(): void
{
    Hash::extend('pepper', function ($app) {
        return new PepperHasher(
            pepper: config('app.hash_pepper'),
            rounds: config('hashing.bcrypt.rounds', 12),
        );
    });
}
```

閉包的引數是容器實例。由於 `extend()` 會將閉包綁定到 `HashManager`，在閉包內也可以透過 `$this` 呼叫 `HashManager` 的方法。

pepper 在 `.env` 檔案中管理。變更 pepper 後，既有的雜湊將無法驗證，因此一旦決定就不要再變更。

```ini theme={null}
# .env
HASH_DRIVER=pepper
HASH_PEPPER=這裡填入足夠長的隨機字串
```

```php theme={null}
// config/app.php
'hash_pepper' => env('HASH_PEPPER'),
```

> [!WARNING]
>
> `HASH_PEPPER` 是機密資訊。請在 `.env` 中管理，不要提交到版本控制。變更或遺失 pepper 後，既有的密碼將無法驗證。

## 確認運作

註冊驅動後，`Hash` Facade 既有的呼叫可以照常運作。

```php theme={null}
use Illuminate\Support\Facades\Hash;

$hash = Hash::make('password123');

Hash::check('password123', $hash); // true
Hash::check('wrong', $hash);       // false

// 明確指定驅動
Hash::driver('bcrypt')->make('password123');
```

`Hash::driver()` 會呼叫 `HashManager::driver()`，回傳指定名稱的驅動。`Hash::make()` 使用預設驅動，因此設定 `HASH_DRIVER=pepper` 後就會使用 `pepper` 驅動。

### 對既有雜湊的影響

切換 `HASH_DRIVER` 或變更 pepper 後，既有的雜湊將無法透過 `check()` 驗證。pepper 一旦決定就不要再變更。對於已有使用者的應用程式，需要在切換驅動之前設計好遷移方式。

## 總結

| 想做的事 | 方法 |
| - | - |
| 註冊驅動 | `Hash::extend('name', fn ($app) => new Hasher)` |
| 切換預設驅動 | `HASH_DRIVER=name` |
| 明確使用驅動 | `Hash::driver('name')` |
| 驅動的契約 | 實作 `Illuminate\Contracts\Hashing\Hasher` |

## 下一步

> [card] [自訂驗證 Guard 的實作](https://kawax.biz/zh-TW/advanced/custom-auth-guard.md)
>
> 從 Guard 實作的角度說明使用 `Hash::check()` 的驗證機制。

> [card] [雜湊（Hashing）](https://kawax.biz/zh-TW/hashing.md)
>
> 了解 bcrypt 與 Argon2 的標準用法與設定。


## Related topics

- [雜湊（Hashing）](https://kawax.biz/zh-TW/hashing.md)
- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)
- [套件的自訂 Session 驅動](https://kawax.biz/zh-TW/advanced/package-session-drivers.md)
- [核心套件與自訂驅動 - Feedable](https://kawax.biz/zh-TW/packages/feedable/core.md)
- [Eloquent 的自訂 Cast](https://kawax.biz/zh-TW/advanced/eloquent-casts.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.