# Hashing

- [Introduction](#introduction)
- [Configuration](#configuration)
- [Basic usage](#basic-usage)
    - [Hashing passwords](#hashing-passwords)
    - [Storing hashes](#storing-hashes)
    - [Verifying that a password matches a hash](#verifying-that-a-password-matches-a-hash)
    - [Determining if a password needs to be rehashed](#determining-if-a-password-needs-to-be-rehashed)

<a name="introduction"></a>

## Introduction


`hash` パッケージは bcryptでユーザーのパスワードをハッシュ化します。Bcrypt は処理時間を調整でき、ハードウェアの高速化に応じて増やせるため、パスワードに適しています。パスワードのハッシュ化は遅いほうが安全です。1回の推測に時間がかかるほど、盗まれたハッシュの解読にも時間がかかります。


通常は `hash` パッケージを頻繁に呼ぶ必要はありません。[Authentication](/ja/go/docs/authentication) がログイン時にハッシュを確認して自動更新し、パスワード変更時には新しい値をハッシュ化します。登録ハンドラーやシーダなどでユーザーを作成するときに `hash.Make` を直接呼び出してください。

<a name="configuration"></a>

## Configuration


Laravel はデフォルトで、多くのアプリケーションに適した bcrypt の 12 ラウンドでハッシュ化します。`BCRYPT_ROUNDS` でコストを変更できます。ラウンドを1つ増やすたびに、処理時間は2倍になります。

```ini
BCRYPT_ROUNDS=12
```


新しいアプリケーションのテストと同様に [`laraveltest.New`](/ja/go/docs/testing#configuring-your-tests) を使うテストでは、高速に実行するため自動的に4ラウンドを使用します。

<a name="basic-usage"></a>

## Basic usage

<a name="hashing-passwords"></a>

### Hashing passwords


コンテキストとパスワードを渡して `hash.Make` を呼ぶと、`BCRYPT_ROUNDS` のラウンド数でハッシュ化し、users テーブルへ保存するハッシュを返します。次の登録ハンドラーはフォームのパスワードをハッシュ化してユーザーを作成します。

```go
package registrations

import (
	"go.laravel.com/hash"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type SignUp struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

func (f *SignUp) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Name, rule.Required, rule.Max(255)),
		rule.Field(&f.Email, rule.Required, rule.Email),
		rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
	)
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[SignUp]()
	if err != nil {
		return web.Fail(err)
	}

	hashed, err := hash.Make(r, form.Password)
	if err != nil {
		return web.Fail(err)
	}

	user := models.User{Name: form.Name, Email: form.Email, Password: hashed}
	if err := model.Create(r, &user); err != nil {
		return web.Fail(err)
	}

	return web.Redirect("/login")
}
```


ハンドラーは `r` を渡します。[seeder](/ja/go/docs/seeding)、[command](/ja/go/docs/console)、[queued job](/ja/go/docs/queues) は受け取った `ctx` を `hash.Make(ctx, "password")` のように渡します。

<a name="password-length"></a>

#### Password length


Bcrypt はパスワードの先頭 72 バイトだけを使用するため、`Make` は長すぎる値を `hash.ErrTooLong` で拒否します。このエラーはユーザーをフォームに戻さず、`422` エラーページを返します。上の登録フォームのように、パスワードフィールドへ `hash.Password` ルールを指定してください。すると長いパスワードはバリデーションで失敗し、パスワードフィールドに「パスワードフィールドは 72 バイトを超えてはいけません。」と表示されます。


`rule.Max(72)` は文字数を数えるため不十分です。ASCII 以外の文字は複数バイトになります。たとえば日本語25文字のパスフレーズは `rule.Max(72)` を通過しますが、75バイトです。

<a name="storing-hashes"></a>

### Storing hashes


ユーザーモデルの `string` フィールドへハッシュを保存し、`json:"-"` タグを付けてください。新しいアプリケーションの `models/user.go` にある `User` モデルには設定済みです。ほかのフィールドを省くと次のとおりです。

```go
package models

type User struct {
	ID       int64  `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"-"`
}
```


`json:"-"` タグは、ユーザーを含む Inertia ページや JSON レスポンスからハッシュを除外します。タグがないとブラウザへパスワードハッシュが送られるため、ハッシュを持つすべてのフィールドに付けてください。

<a name="verifying-that-a-password-matches-a-hash"></a>

### Verifying that a password matches a hash


`hash.Check` は、フォームから受け取った平文パスワードなどが保存済みハッシュに一致するかを検証します。誤ったパスワードや読み取れないハッシュには `false` を返します。

```go
import "go.laravel.com/hash"

if hash.Check(form.Password, user.Password) {
	// The passwords match...
}
```


ユーザーをログインさせるには [`auth.Attempt`](/ja/go/docs/authentication#attempting-a-login) を使用してください。パスワードを確認し、アカウントの有無にかかわらず失敗まで同じ時間をかけます。

<a name="determining-if-a-password-needs-to-be-rehashed"></a>

### Determining if a password needs to be rehashed


`BCRYPT_ROUNDS` を増やしても保存済みのハッシュは以前のラウンド数のままです。`hash.NeedsRehash` は現在と異なるラウンド数のハッシュに `true` を返します。`Check` が成功した直後、平文を保持している間に再度ハッシュ化してください。

```go
import (
	"go.laravel.com/db"
	"go.laravel.com/hash"
	"go.laravel.com/model"
	"go.laravel.com/web"
)

if hash.Check(form.Password, user.Password) {
	if hash.NeedsRehash(r, user.Password) {
		hashed, err := hash.Make(r, form.Password)
		if err != nil {
			return web.Fail(err)
		}

		if err := model.Update(r, &user, db.Values{"password": hashed}); err != nil {
			return web.Fail(err)
		}
	}

	// Log the user in...
}
```


`auth.Attempt` がこの処理を行うため、`BCRYPT_ROUNDS` を増やすと各ユーザーの次回ログイン時に更新されます。新しいハッシュは [other devices](/ja/go/docs/authentication#changing-a-password) からもログアウトさせるため、ラウンドを増やすと各ユーザーはほかのデバイスから一度ログアウトされます。