Documentation
¶
Overview ¶
Package encryption encrypts and authenticates small messages, such as session cookies, with the application key (APP_KEY).
enc, err := encryption.ForApp(app)
token := enc.EncryptString("user:42", "password-reset")
msg, err := enc.DecryptString(token, "password-reset")
Messages are sealed with AES-256-GCM under a key derived for each message (HKDF-SHA256 with a random salt), so there is no practical limit on how many messages one key can encrypt. The keys of recent messages are cached (the last 1024 to 2048), so opening the same message again, as a session cookie on each request, skips the derivation. The context string is authenticated with the message: a ciphertext made for one purpose can't be used for another. Keys rotate by moving the old key to APP_PREVIOUS_KEYS: new messages use APP_KEY, old ones still decrypt.
An Encrypter is safe for concurrent use.
Index ¶
Constants ¶
const KeySize = appkey.Size
KeySize is the size of a key in bytes.
Variables ¶
var ErrInvalid = errors.New("encryption: invalid message")
ErrInvalid is returned for a message that was tampered with, made for another context, or encrypted with a key that is no longer configured.
Functions ¶
func GenerateKey ¶
func GenerateKey() string
GenerateKey returns a new random key in the "base64:…" form of APP_KEY.
Types ¶
type Encrypter ¶
type Encrypter struct {
// contains filtered or unexported fields
}
Encrypter encrypts with its first key and decrypts with any of them.
func ForApp ¶
ForApp returns an Encrypter for the application's APP_KEY and APP_PREVIOUS_KEYS. It fails, suggesting a freshly generated key, if APP_KEY is not set.
func New ¶
New returns an Encrypter that encrypts with current and also decrypts messages written with the previous keys. Every key must be KeySize bytes.
func (*Encrypter) Decrypt ¶
Decrypt opens a ciphertext made by Encrypt with the same context. It returns ErrInvalid if the message was changed, made for another context, or sealed with a key that isn't configured.
func (*Encrypter) DecryptString ¶
DecryptString reverses EncryptString.
func (*Encrypter) Encrypt ¶
Encrypt seals plaintext for the given context (any string naming the purpose, such as a cookie name) and returns the ciphertext.
func (*Encrypter) EncryptString ¶
EncryptString is Encrypt for strings; the result is URL-safe base64 without padding, fit for cookies and URLs.