跳至正文

Hashing ​

Introduction ​

The hash package hashes your users' passwords with bcrypt. Bcrypt is a great choice for passwords because you can tune how long a hash takes, and raise it as hardware gets faster. Slow is good when hashing passwords: the longer each guess takes, the longer an attacker needs to crack a stolen hash.

In most applications, you won't need to call the hash package often. Authentication checks password hashes when users log in, upgrades them automatically, and hashes new passwords when users change them. Call hash.Make yourself when you create a user, such as in a sign-up handler or a seeder.

Configuration ​

By default, Laravel hashes passwords with 12 rounds of bcrypt, which is fine for most applications. You may change the work factor with BCRYPT_ROUNDS. Each extra round doubles the time a hash takes:

ini
BCRYPT_ROUNDS=12

Tests that use laraveltest.New, as the tests in new applications do, automatically hash with 4 rounds to stay fast.

Basic usage ​

Hashing passwords ​

You may hash a password by calling hash.Make with the context and the password. It hashes with the rounds that BCRYPT_ROUNDS sets, and returns the hash to store in your users table. This sign-up handler hashes the password from its form and creates the user:

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")
}

A handler passes r. A seeder, a command, or a queued job passes the ctx it received: hash.Make(ctx, "password").

Password length ​

Bcrypt uses only the first 72 bytes of a password, so Make refuses a longer one with hash.ErrTooLong, which responds with a 422 error page rather than sending the user back to the form. Give your password fields the hash.Password rule, as the sign-up form above does. A long password then fails validation instead, and the user sees "The password field must not be greater than 72 bytes." on the password field.

rule.Max(72) isn't enough, because it counts characters, and a character outside ASCII takes more than one byte. For example, a passphrase of 25 Japanese characters passes rule.Max(72), but it takes 75 bytes.

Storing hashes ​

Store a hash in a string field of your user model, and tag the field json:"-". The User model in new applications, in models/user.go, already does. Here it is with its other fields left out:

go
package models

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

The json:"-" tag keeps the hash out of every Inertia page and JSON response that includes the user. Without it, those responses would send the user's password hash to the browser, so keep the tag on any field that holds a hash.

Verifying that a password matches a hash ​

hash.Check verifies that a plain-text password, such as the one from your form, matches the user's stored hash. It returns false for a wrong password, and for a hash it can't read:

go
import "go.laravel.com/hash"

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

To log a user in, use auth.Attempt instead. It checks the password for you, and takes as long to fail whether or not the account exists.

Determining if a password needs to be rehashed ​

When you raise BCRYPT_ROUNDS, the hashes already in your database keep their old rounds. hash.NeedsRehash returns true for a hash made with rounds other than your current setting. Hash the password again right after Check accepts it, while you still have the plain text:

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 does this for you, so after you raise BCRYPT_ROUNDS, each user's hash upgrades the next time they log in. A new hash also logs the user out of their other devices, so raising the rounds logs each user out of their other devices once.