> ## 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 파사드에서 투명하게 사용하는 방법을 프레임워크 소스 코드를 바탕으로 해설합니다.

## 개요

`Hash` 파사드는 `Illuminate\Hashing\HashManager`의 프록시입니다. `HashManager`는 `Illuminate\Support\Manager`를 상속한 드라이버 매니저로, `bcrypt`·`argon`·`argon2id` 세 가지를 기본으로 갖추고 있습니다.

공식 문서가 다루는 범위는 `HASH_DRIVER`를 통한 전환까지이지만, `HashManager`는 `Manager`의 구조를 그대로 사용하므로 독자적인 해시 드라이버를 추가할 수 있습니다. 여기서는 비밀번호에 서버 측 비밀 키(페퍼)를 섞은 뒤 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()`에서 빈 해시를 다루는 처리 등을 물려받을 수 있습니다.

## 페퍼를 적용한 해셔 구현

비밀번호를 그대로 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()`가 전달받은 평문을 그대로 검증해 버리기 때문입니다. 페퍼를 적용한 값으로 검증해야 하므로 여기서는 오버라이드합니다.

## 드라이버 등록

커스텀 드라이버는 `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`의 메서드를 호출할 수도 있습니다.

페퍼는 `.env` 파일에서 관리합니다. 페퍼를 변경하면 기존 해시를 검증할 수 없게 되므로, 한 번 정한 뒤에는 변경하지 마세요.

```ini theme={null}
# .env
HASH_DRIVER=pepper
HASH_PEPPER=여기에-충분히-긴-무작위-문자열
```

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

> [!WARNING]
>
> `HASH_PEPPER`는 비밀 정보입니다. `.env`에서 관리하고 버전 관리에 커밋하지 마세요. 페퍼를 변경하거나 분실하면 기존 비밀번호를 검증할 수 없게 됩니다.

## 동작 확인

드라이버를 등록하면 `Hash` 파사드의 기존 호출은 그대로 동작합니다.

```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`를 전환하거나 페퍼를 변경하면 기존 해시는 `check()`로 검증할 수 없게 됩니다. 페퍼는 한 번 정한 뒤에는 변경하지 마세요. 기존 사용자가 있는 애플리케이션에서는 드라이버를 전환하기 전에 마이그레이션 방법을 설계해야 합니다.

## 정리

| 하고 싶은 일 | 방법 |
| - | - |
| 드라이버 등록 | `Hash::extend('name', fn ($app) => new Hasher)` |
| 기본 드라이버 전환 | `HASH_DRIVER=name` |
| 드라이버를 명시적으로 사용 | `Hash::driver('name')` |
| 드라이버 계약 | `Illuminate\Contracts\Hashing\Hasher` 구현 |

## 다음 단계

> [card] [커스텀 인증 가드 구현](https://kawax.biz/ko/advanced/custom-auth-guard.md)
>
> `Hash::check()`를 사용하는 인증 구조를 가드 구현 측면에서 해설합니다.

> [card] [해시(Hashing)](https://kawax.biz/ko/hashing.md)
>
> bcrypt와 Argon2의 표준적인 사용법과 설정을 확인할 수 있습니다.


## Related topics

- [해시(Hashing)](https://kawax.biz/ko/hashing.md)
- [고급 주제](https://kawax.biz/ko/advanced/index.md)
- [패키지의 커스텀 세션 드라이버](https://kawax.biz/ko/advanced/package-session-drivers.md)
- [코어 패키지와 커스텀 드라이버 - Feedable](https://kawax.biz/ko/packages/feedable/core.md)
- [Laravel Sentinel — 라우트 보호 미들웨어 조사](https://kawax.biz/ko/blog/sentinel-introduction.md)


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