Encryption
Introduction
Sometimes you need to store a secret that you'll read back later, such as a user's API token for another service. A hash won't do, because you can't get the value back from it. The crypt package encrypts values with AES-256 and signs each one with a message authentication code (MAC), so a value that someone has changed fails to decrypt.
Laravel also uses the encrypter for your cookies, including the session cookie, so your application depends on it even if you never call the package yourself.
Configuration
The encrypter uses the key in the APP_KEY variable of your .env file. The Laravel CLI sets it when you create your application. If you don't have a .env file yet, such as after you clone your application onto another machine, run the key:generate command. It creates .env from .env.example and writes a secure random key:
laravel key:generateKeep the key secret. Anyone who has it can read your encrypted values, forge your cookies, and create signed URLs that your application trusts.
By default, Laravel encrypts with AES-256-CBC. You may choose AES-128-CBC, AES-128-GCM, or AES-256-GCM with APP_CIPHER. Set your cipher before you generate APP_KEY, because the AES-128 ciphers take a shorter key. Changing the cipher later makes everything you've encrypted unreadable, even with the old keys listed in APP_PREVIOUS_KEYS.
Rotating your encryption key
If you change your application's key, every encrypted cookie becomes unreadable, including the session cookie, so all your users are logged out. Anything else you encrypted with the old key can't be decrypted either.
To avoid this, list your old keys in APP_PREVIOUS_KEYS, separated by commas, exactly as they were set in APP_KEY:
APP_KEY=base64:J63qRTDLub5NuZvP+kb8YIorGS6qFYHKVo6u7179stY=
APP_PREVIOUS_KEYS=base64:2nLsGFGzyoae2ax3EF2Lyq/hH6QghBGLIq5uL+Gp8/w=Laravel always encrypts with the current key. To decrypt, it tries the current key first, then each previous key, so your users stay logged in, and the signed URLs and password reset links you've already sent keep working.
To rotate the key, copy the current APP_KEY into APP_PREVIOUS_KEYS, then generate a new key. key:generate refuses to replace a key that's already set, so pass --force:
laravel key:generate --forceThe values in your database stay encrypted with the old key until something writes them again, so keep the old key in APP_PREVIOUS_KEYS until you've moved those rows to the new key. To learn how, check out Re-encrypting columns with a new key.
Using the encrypter
The crypt package provides functions for encrypting and decrypting strings and other values yourself. Each function finds your key in the context you pass it, so a handler passes r, and a job or a command passes the ctx it received. If you'd like Laravel to encrypt and decrypt a model field for you, check out Encrypting model columns.
Encrypting a value
You may encrypt a string with crypt.EncryptString. Suppose your users table has a nullable github_token column, held in a *string field on your User model, and your settings page lets users paste a GitHub token. This handler, on a route for logged-in users, encrypts the GitHub token before storing it:
package settings
import (
"go.laravel.com/crypt"
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type GitHubToken struct {
Token string `json:"token"`
}
func (f *GitHubToken) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Token, rule.Required))
}
func StoreGitHubToken(r *web.Request) *web.Response {
form, err := r.Validate[GitHubToken]()
if err != nil {
return web.Fail(err)
}
githubToken, err := crypt.EncryptString(r, form.Token)
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{"github_token": githubToken}); err != nil {
return web.Fail(err)
}
return web.Redirect("/settings")
}Decrypting a value
You may decrypt a value with crypt.DecryptString. It returns an error when the value can't be decrypted, such as when someone changed it, or when it was encrypted with a key you no longer have. This handler decrypts the token that the handler above stored, and calls GitHub's API with it through the HTTP client to sync the user's repositories:
import "go.laravel.com/httpclient"
func SyncRepositories(r *web.Request) *web.Response {
user := r.User[models.User]()
if user.GitHubToken == nil {
return web.Redirect("/settings")
}
token, err := crypt.DecryptString(r, *user.GitHubToken)
if err != nil {
return web.Redirect("/settings").With("status", "Please connect your GitHub account again.")
}
if _, err := httpclient.Token(token).Get(r, "https://api.github.com/user/repos"); err != nil {
return web.Fail(err)
}
return web.Redirect("/repositories")
}When you don't need to handle the failure, pass the error to web.Fail, and the request gets a server error instead.
Encrypting other types
To encrypt a value that isn't a string, such as a struct, use crypt.Encrypt. It encrypts any value that encodes to JSON, and crypt.Decrypt turns it back into your type. This social login callback, on a route for logged-in users, stores the token GitHub issues in the same nullable github_token column:
package github
import (
"go.laravel.com/auth/social"
"go.laravel.com/crypt"
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Callback(r *web.Request) *web.Response {
profile, err := social.User(r, social.GitHub)
if err != nil {
return web.Fail(err)
}
githubToken, err := crypt.Encrypt(r, profile.Token)
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{"github_token": githubToken}); err != nil {
return web.Fail(err)
}
return web.Redirect("/repositories")
}When you read the column back, give crypt.Decrypt the type you encrypted in brackets:
token, err := crypt.Decrypt[social.Token](r, *user.GitHubToken)
if err != nil {
return web.Fail(err)
}
// Call GitHub with token.Access...Encrypting model columns
When you store a sensitive value on a model, such as a third-party API token entered on a settings page, declare the field as a crypt.Encrypted[string]. Laravel encrypts the value whenever a create or an update writes it, and decrypts it whenever a query loads the model, so your code works with the plain value while the database holds only ciphertext.
Ciphertext is longer than the value it encrypts, and its length varies, so give the column a text type in its migration, such as table.Text("github_token").Nullable(). Then declare the field on the model. A pointer holds a nullable column, so a user without a token has a nil field:
// models/user.go
package models
import "go.laravel.com/crypt"
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
GitHubToken *crypt.Encrypted[string] `json:"-" db:"github_token"`
}The db tag names the column, because the field's name in snake case would be git_hub_token.
Like a password hash, an encrypted value stays off your responses. An Encrypted value prints as Encrypted([redacted]) and refuses to encode as JSON, so a page or a JSON response that includes the model fails with an error until you tag the field json:"-". When a response needs the plain value, pass it yourself.
A create or an update takes the plain value. For example, this handler stores an API token submitted from a settings form:
package settings
import (
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type GitHubToken struct {
Token string `json:"token"`
}
func (f *GitHubToken) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Token, rule.Required))
}
func StoreGitHubToken(r *web.Request) *web.Response {
form, err := r.Validate[GitHubToken]()
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{"github_token": form.Token}); err != nil {
return web.Fail(err)
}
return web.Redirect("/settings")
}To set the field yourself, such as before you call model.Create, wrap the plain value with crypt.NewEncrypted, as in user.GitHubToken = new(crypt.NewEncrypted(token)).
A loaded model holds the decrypted value in the field's Value, so you can pass it to any function that takes a string:
import "go.laravel.com/httpclient"
func SyncRepositories(r *web.Request) *web.Response {
user := r.User[models.User]()
if user.GitHubToken == nil {
return web.Redirect("/settings")
}
_, err := httpclient.Token(user.GitHubToken.Value).
Get(r, "https://api.github.com/user/repos")
if err != nil {
return web.Fail(err)
}
// ...
return web.Redirect("/repositories")
}Loading decrypts with your current key, then with each key in APP_PREVIOUS_KEYS. When no key decrypts a value, such as one you encrypted with a key you no longer have, the query fails with an error that names the column.
Lists and structs
To encrypt a list or a map, declare the field as an Encrypted of a slice or a map, such as crypt.Encrypted[[]string] or crypt.Encrypted[map[string]string], and Laravel encrypts its JSON. This field holds a user's two-factor recovery codes:
RecoveryCodes *crypt.Encrypted[[]string] `json:"-"`A create or an update takes the plain slice, as in db.Values{"recovery_codes": codes}, and the loaded field holds it in Value, so len(user.RecoveryCodes.Value) counts the codes.
To encrypt a struct of your own, give its fields json tags, as you would for a JSON column. Here, a project stores the URL and signing secret of a webhook it calls after each deployment:
package models
import "go.laravel.com/crypt"
type DeployHook struct {
URL string `json:"url"`
Secret string `json:"secret"`
}
type Project struct {
ID int64 `json:"id"`
DeployHook *crypt.Encrypted[DeployHook] `json:"-"`
}An update takes the plain struct:
hook := models.DeployHook{URL: url, Secret: secret}
if err := model.Update(r, &project, db.Values{"deploy_hook": hook}); err != nil {
return web.Fail(err)
}The social login social.Token type also works inside a crypt.Encrypted[social.Token] for storing OAuth tokens. A crypt.Encrypted[string] encrypts the raw string, while other types are encoded as JSON first.
Querying encrypted columns
Because encrypting the same value twice gives two different ciphertexts, the database can't find a row by an encrypted value. A condition such as Where("github_token", "=", token) matches no row, though WhereNull and WhereNotNull still work. When you need to look up a row by a secret, such as an API key a client sends, store a hash of it in a separate indexed column and query that column instead.
Re-encrypting columns with a new key
After you rotate your encryption key, the values in your database stay encrypted with the old key until something writes them again. UsesPreviousKey reports whether a previous key decrypted a field's value. An update skips a column whose value hasn't changed, but it always writes a field that a previous key decrypted, so assigning the same value encrypts it again with the current key. Before you remove the old key from APP_PREVIOUS_KEYS, re-encrypt the rows that still need it. For example, this command moves every user's GitHub token to the current key:
package commands
import (
"context"
"go.laravel.com/console"
"go.laravel.com/db"
"go.laravel.com/model"
"app/models"
)
// ReencryptTokens encrypts every user's GitHub token with the current key.
type ReencryptTokens struct{}
func (*ReencryptTokens) Name() string { return "users:reencrypt-tokens" }
func (*ReencryptTokens) Description() string {
return "Encrypt every user's GitHub token with the current key"
}
func (*ReencryptTokens) Run(ctx context.Context, c *console.Console) error {
users := model.Query[models.User]().WhereNotNull("github_token")
for user, err := range users.LazyByID(ctx, 100) {
if err != nil {
return err
}
if !user.GitHubToken.UsesPreviousKey() {
continue
}
if err := model.Update(ctx, &user, db.Values{
"github_token": user.GitHubToken.Value,
}); err != nil {
return err
}
}
c.Success("Tokens re-encrypted.")
return nil
}Add the command to the All list in commands/commands.go, as the console guide's section on registering commands describes, then run it after you deploy the new key:
laravel users:reencrypt-tokens