securecookie

package
v0.4.7 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package securecookie encodes and decodes authenticated and optionally encrypted cookie values.

A Codec serializes an arbitrary value, optionally encrypts it with AES-CTR, and signs the result with HMAC-SHA256. The signature also covers the cookie name and a timestamp, so values cannot be moved between cookies or replayed outside their validity window.

Encoded layout (before the outer base64):

timestamp | base64(payload) | base64(hmac)

where payload is "serialized" in sign-only mode, or "iv || aes-ctr(serialized)" when a block key is configured.

The API is dependency-free and uses only the standard library.

Index

Constants

View Source
const (
	// DefaultMaxAge is the default validity window for an encoded value.
	DefaultMaxAge = 30 * 24 * 60 * 60 // 30 days in seconds
	// DefaultMaxLength is the default maximum length of an encoded value.
	DefaultMaxLength = 4096
)

Variables

View Source
var (
	// ErrHashKeyRequired is returned when New is called without a hash key.
	ErrHashKeyRequired = errors.New("securecookie: hash key is required")

	// ErrInvalidBlockKeySize is returned when the block key length is not a
	// valid AES key size (16, 24 or 32 bytes).
	ErrInvalidBlockKeySize = errors.New("securecookie: block key must be 16, 24 or 32 bytes")

	// ErrNoCodecs is returned when a Codecs slice is empty.
	ErrNoCodecs = errors.New("securecookie: no codecs configured")

	// ErrMACInvalid is returned when the message authentication code does not
	// match, meaning the value was tampered with or signed with another key.
	ErrMACInvalid = errors.New("securecookie: the value MAC is invalid")

	// ErrTimestampExpired is returned when the value is older than the
	// configured max age.
	ErrTimestampExpired = errors.New("securecookie: expired timestamp")

	// ErrTimestampTooNew is returned when the value timestamp is newer than the
	// configured min age (clock skew or replay).
	ErrTimestampTooNew = errors.New("securecookie: timestamp is too new")

	// ErrValueTooLong is returned when the encoded value exceeds the configured
	// max length.
	ErrValueTooLong = errors.New("securecookie: the value is too long")

	// ErrDecode is returned when the encoded value cannot be parsed.
	ErrDecode = errors.New("securecookie: error decoding value")
)

Functions

func GenerateRandomKey

func GenerateRandomKey(length int) []byte

GenerateRandomKey returns a cryptographically secure random key of the given length in bytes. Common lengths are 32 or 64 for hash keys and 16, 24 or 32 for block (AES) keys. It panics if the system random source fails, which should never happen in practice.

Types

type Codec

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

Codec encodes and decodes secure cookie values. A zero Codec is not usable; construct one with New.

func New

func New(hashKey, blockKey []byte, opts ...Option) *Codec

New returns a Codec that signs values with hashKey using HMAC-SHA256 and, if blockKey is non-empty, encrypts them with AES-CTR.

hashKey is required and should be at least 32 bytes. blockKey, when set, must be 16, 24 or 32 bytes to select AES-128, AES-192 or AES-256. It panics on invalid keys; use NewWithError if you need to handle the error.

func NewWithError

func NewWithError(hashKey, blockKey []byte, opts ...Option) (*Codec, error)

NewWithError is like New but returns an error instead of panicking on invalid keys.

func (*Codec) Decode

func (c *Codec) Decode(name, encoded string, dst any) error

Decode verifies the encoded value's signature and timestamp, decrypts it if necessary, and deserializes the result into dst, which must be a non-nil pointer.

func (*Codec) Encode

func (c *Codec) Encode(name string, value any) (string, error)

Encode serializes value, optionally encrypts it, signs it together with name and the current timestamp, and returns a URL-safe base64 string.

func (*Codec) SetMaxAge

func (c *Codec) SetMaxAge(seconds int)

SetMaxAge sets the maximum age in seconds for decoding. A value of 0 disables the check. Intended to be called at setup time (for example by a session store) before the codec is shared across goroutines.

type Codecs

type Codecs []*Codec

Codecs is an ordered set of codecs used for key rotation. Encoding always uses the first codec; decoding tries each codec in turn until one succeeds.

To rotate keys, prepend a Codec built from the new key pair and keep the old ones around long enough for existing cookies to expire, then drop them.

func CodecsFromPairs

func CodecsFromPairs(opts []Option, keyPairs ...[]byte) Codecs

CodecsFromPairs returns a Codecs built from a sequence of key pairs. Each pair is (hashKey, blockKey); pass a nil or empty blockKey to disable encryption for that pair. The shared opts are applied to every codec.

codecs := securecookie.CodecsFromPairs(nil,
	newHashKey, newBlockKey,
	oldHashKey, oldBlockKey,
)

func (Codecs) Decode

func (cs Codecs) Decode(name, encoded string, dst any) error

Decode tries each codec in order and returns the first successful result. If all fail, it returns the last error (joined for inspection with errors.Is).

func (Codecs) Encode

func (cs Codecs) Encode(name string, value any) (string, error)

Encode encodes value with the first codec.

type GobSerializer

type GobSerializer struct{}

GobSerializer encodes values using encoding/gob. It is the default and supports arbitrary Go types. Concrete types stored behind an interface value must be registered with gob.Register.

func (GobSerializer) Deserialize

func (GobSerializer) Deserialize(src []byte, dst any) error

Deserialize implements Serializer.

func (GobSerializer) Serialize

func (GobSerializer) Serialize(src any) ([]byte, error)

Serialize implements Serializer.

type JSONSerializer

type JSONSerializer struct{}

JSONSerializer encodes values using encoding/json. It produces smaller, human-readable payloads but only supports JSON-compatible types.

func (JSONSerializer) Deserialize

func (JSONSerializer) Deserialize(src []byte, dst any) error

Deserialize implements Serializer.

func (JSONSerializer) Serialize

func (JSONSerializer) Serialize(src any) ([]byte, error)

Serialize implements Serializer.

type Option

type Option func(*Codec)

Option configures a Codec.

func WithMaxAge

func WithMaxAge(seconds int) Option

WithMaxAge sets the maximum age in seconds of a value to be decoded. A value of 0 disables the check. Defaults to DefaultMaxAge.

func WithMaxLength

func WithMaxLength(n int) Option

WithMaxLength sets the maximum length of the encoded value. A value of 0 disables the check. Defaults to DefaultMaxLength.

func WithMinAge

func WithMinAge(seconds int) Option

WithMinAge sets the minimum age in seconds of a value to be decoded. A value of 0 disables the check. Useful to reject values that appear to come from the future due to clock skew.

func WithNow

func WithNow(fn func() time.Time) Option

WithNow overrides the clock used for timestamps. Intended for tests.

func WithSerializer

func WithSerializer(s Serializer) Option

WithSerializer sets the serializer used to encode values. Defaults to GobSerializer.

type Serializer

type Serializer interface {
	// Serialize encodes src into a byte slice.
	Serialize(src any) ([]byte, error)
	// Deserialize decodes src into dst. dst must be a non-nil pointer.
	Deserialize(src []byte, dst any) error
}

Serializer converts a value to and from a byte slice before it is signed and optionally encrypted.

Jump to

Keyboard shortcuts

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