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 ¶
- Variables
- func Decrypt[T any](ctx context.Context, payload string) (T, error)
- func DecryptString(ctx context.Context, payload string) (string, error)
- func Encrypt(ctx context.Context, value any) (string, error)
- func EncryptString(ctx context.Context, value string) (string, error)
- func GenerateKey(cipher Cipher) string
- type Cipher
- type Encrypted
- type Encrypter
- func (e *Encrypter) Cipher() Cipher
- func (e *Encrypter) Decrypt[T any](payload string) (T, error)
- func (e *Encrypter) DecryptString(payload string) (string, error)
- func (e *Encrypter) Encrypt(value any) (string, error)
- func (e *Encrypter) EncryptString(value string) string
- func (e *Encrypter) Keys() [][]byte
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
KeySize returns the required key length in bytes for c (16 for AES-128, 32 for AES-256).
func (*Cipher) UnmarshalText ¶
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 ¶
NewEncrypted wraps v in an Encrypted column value with T inferred from v.
func (*Encrypted[T]) Decrypt ¶
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 ¶
Encrypt encrypts Encrypted.Value with encrypter's current key and returns the ciphertext string stored in the database column.
func (Encrypted[T]) Format ¶
Format writes Encrypted([redacted]) for every fmt verb so the secret stays out of logs.
func (Encrypted[T]) MarshalJSON ¶
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 ¶
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 ¶
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 ¶
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) Decrypt ¶
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 ¶
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 ¶
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 ¶
EncryptString encrypts value with the current key and returns the base64-encoded payload.