crypt

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package crypt encrypts and decrypts values using AES with the application's keys.

EncryptString and DecryptString use the keys configured on the application in ctx, passing the request in a handler or the context of a job, listener, or command:

payload, err := crypt.EncryptString(r, token)
if err != nil {
	return web.Fail(err)
}

token, err := crypt.DecryptString(r, payload)

Encrypter encrypts values into base64-encoded JSON payloads using AES-CBC with an HMAC-SHA256 MAC or AES-GCM. Decryption tries the current key first and then each previous key, so you can rotate APP_KEY without invalidating existing ciphertexts. Call New to build an Encrypter with your own keys:

encrypter, err := crypt.New(key, crypt.AES256CBC)
if err != nil {
	return err
}

payload := encrypter.EncryptString("secret")
secret, err := encrypter.DecryptString(payload)

To encrypt database columns automatically on read and write, use the Encrypted generic field type on your models.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidPayload is returned when a payload is not valid base64-encoded
	// encrypted JSON or has an IV of the wrong length.
	ErrInvalidPayload = errors.New("crypt: the payload is invalid")
	// ErrInvalidMAC is returned when a CBC payload's HMAC does not match any
	// configured key, indicating tampering or a wrong key.
	ErrInvalidMAC = errors.New("crypt: the MAC is invalid")
	// ErrDecrypt is returned when ciphertext decryption, padding verification,
	// GCM tag authentication, or JSON decoding fails.
	ErrDecrypt = errors.New("crypt: could not decrypt the data")
	// ErrMissingKey is returned when no application encryption key (APP_KEY) is
	// configured.
	ErrMissingKey = errors.New("crypt: no application encryption key has been specified; run `go run . key:generate` to create one")
)

Sentinel errors returned by encryption and decryption operations. Match them with errors.Is.

Functions

func Decrypt

func Decrypt[T any](ctx context.Context, payload string) (T, error)

Decrypt decrypts a payload produced by Encrypt and decodes its JSON as T using the keys of the application in ctx:

token, err := crypt.Decrypt[OAuthToken](r, payload)

It returns ErrMissingKey if the application has no APP_KEY, or ErrInvalidPayload, ErrInvalidMAC, or ErrDecrypt if decryption or JSON decoding fails. It panics if ctx does not carry an application scope.

func DecryptString

func DecryptString(ctx context.Context, payload string) (string, error)

DecryptString decrypts a payload produced by EncryptString using the keys of the application in ctx, as Encrypter.DecryptString does. It returns ErrMissingKey if the application has no APP_KEY, or ErrInvalidPayload, ErrInvalidMAC, or ErrDecrypt if decryption fails. It panics if ctx does not carry an application scope.

func Encrypt

func Encrypt(ctx context.Context, value any) (string, error)

Encrypt encodes value as JSON and encrypts it using the keys of the application in ctx, as Encrypter.Encrypt does. It returns ErrMissingKey if the application has no APP_KEY, and panics if ctx does not carry an application scope.

func EncryptString

func EncryptString(ctx context.Context, value string) (string, error)

EncryptString encrypts value using the keys of the application in ctx, as Encrypter.EncryptString does. It returns ErrMissingKey if the application has no APP_KEY, and panics if ctx does not carry an application scope.

func GenerateKey

func GenerateKey(cipher Cipher) string

GenerateKey generates a random key sized for cipher and returns it in the "base64:..." format expected by APP_KEY.

Types

type Cipher

type Cipher int

Cipher identifies the AES encryption algorithm used by an Encrypter. The zero value is AES256CBC.

const (
	// AES256CBC selects AES-256 in CBC mode authenticated with HMAC-SHA256.
	AES256CBC Cipher = iota
	// AES128CBC selects AES-128 in CBC mode authenticated with HMAC-SHA256.
	AES128CBC
	// AES256GCM selects AES-256 in GCM authenticated encryption mode.
	AES256GCM
	// AES128GCM selects AES-128 in GCM authenticated encryption mode.
	AES128GCM
)

func ParseCipher

func ParseCipher(name string) (Cipher, error)

ParseCipher parses a cipher name such as "aes-256-gcm", ignoring case. It returns an error if name is not a supported cipher.

func (Cipher) KeySize

func (c Cipher) KeySize() int

KeySize returns the required key length in bytes for c (16 for AES-128, 32 for AES-256).

func (Cipher) String

func (c Cipher) String() string

String returns the cipher's uppercase name, such as "AES-256-CBC".

func (*Cipher) UnmarshalText

func (c *Cipher) UnmarshalText(text []byte) error

UnmarshalText parses text as a cipher name using ParseCipher and stores the result in c.

type Encrypted

type Encrypted[T any] struct {
	// Value holds the decrypted plain value.
	Value T
	// contains filtered or unexported fields
}

Encrypted wraps a model field whose database column is stored encrypted with the application's key, such as a third-party API token. An Encrypted[string] stores encrypted text, while Encrypted with any other type (such as a slice, map, or struct) stores encrypted JSON. Store the column as text, and declare the field as a pointer when the column is nullable so that nil maps to NULL:

type User struct {
	ID            int64                     `json:"id"`
	GitHubToken   *crypt.Encrypted[string]  `json:"-" db:"github_token"`
	RecoveryCodes crypt.Encrypted[[]string] `json:"-"`
}

The db package encrypts Encrypted values when binding query parameters and decrypts columns when scanning into them, using the connection's Encrypter. Model writes also accept the plain value directly, such as db.Values{"github_token": token}.

Decryption tries the current key first and then each previous key. Encrypted.UsesPreviousKey reports whether a previous key was used. Every write encrypts with the current key.

Encrypted refuses to marshal to JSON and formats as Encrypted([redacted]) so secrets cannot leak into responses or logs by accident. Tag Encrypted fields with json:"-".

func NewEncrypted

func NewEncrypted[T any](v T) Encrypted[T]

NewEncrypted wraps v in an Encrypted column value with T inferred from v.

func (*Encrypted[T]) Decrypt

func (e *Encrypted[T]) Decrypt(encrypter *Encrypter, payload string) error

Decrypt decrypts payload using encrypter and stores the result in Encrypted.Value. It returns ErrInvalidPayload, ErrInvalidMAC, or ErrDecrypt if decryption fails, or an error if a non-string value cannot be decoded from JSON into T.

func (Encrypted[T]) Encrypt

func (e Encrypted[T]) Encrypt(encrypter *Encrypter) (string, error)

Encrypt encrypts Encrypted.Value with encrypter's current key and returns the ciphertext string stored in the database column.

func (Encrypted[T]) Format

func (Encrypted[T]) Format(f fmt.State, _ rune)

Format writes Encrypted([redacted]) for every fmt verb so the secret stays out of logs.

func (Encrypted[T]) MarshalJSON

func (Encrypted[T]) MarshalJSON() ([]byte, error)

MarshalJSON always returns an error so that a model whose Encrypted field lacks a json:"-" tag fails to encode instead of exposing the secret.

func (Encrypted[T]) UsesPreviousKey

func (e Encrypted[T]) UsesPreviousKey() bool

UsesPreviousKey reports whether Encrypted.Decrypt decrypted the value with a key from APP_PREVIOUS_KEYS instead of the current key. Saving the value again re-encrypts it with the current key.

type Encrypter

type Encrypter struct {
	// contains filtered or unexported fields
}

Encrypter encrypts values with its current key and decrypts payloads using the current key or any configured previous key. It is safe for concurrent use.

func From

func From(ctx context.Context) (*Encrypter, error)

From returns the Encrypter configured for the application in ctx. It returns ErrMissingKey if the application has no APP_KEY, and panics if ctx does not carry an application scope.

func New

func New(key string, cipher Cipher, previous ...string) (*Encrypter, error)

New returns an Encrypter configured with cipher, current key, and optional previous keys for decrypting rotated payloads. Each key may be raw bytes or a "base64:"-prefixed string as returned by GenerateKey and stored in APP_KEY. New returns ErrMissingKey if key is empty, or an error if any key is not valid base64 or does not match Cipher.KeySize.

func (*Encrypter) Cipher

func (e *Encrypter) Cipher() Cipher

Cipher returns the Cipher configured on e.

func (*Encrypter) Decrypt

func (e *Encrypter) Decrypt[T any](payload string) (T, error)

Decrypt decrypts a payload produced by Encrypter.Encrypt and decodes its JSON as T:

token, err := encrypter.Decrypt[OAuthToken](payload)

It returns ErrInvalidPayload, ErrInvalidMAC, or ErrDecrypt if decryption or JSON decoding fails.

func (*Encrypter) DecryptString

func (e *Encrypter) DecryptString(payload string) (string, error)

DecryptString decrypts a payload produced by Encrypter.EncryptString, trying the current key first and then each previous key. It returns ErrInvalidPayload, ErrInvalidMAC, or ErrDecrypt if decryption fails.

func (*Encrypter) Encrypt

func (e *Encrypter) Encrypt(value any) (string, error)

Encrypt encodes value as JSON and encrypts it with the current key. Use Encrypter.EncryptString when encrypting a plain string without JSON encoding.

func (*Encrypter) EncryptString

func (e *Encrypter) EncryptString(value string) string

EncryptString encrypts value with the current key and returns the base64-encoded payload.

func (*Encrypter) Keys

func (e *Encrypter) Keys() [][]byte

Keys returns the raw encryption keys held by e. The first element is the current key used for encryption, followed by any previous keys accepted during decryption.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL