securecookie
Encodes and decodes authenticated, optionally encrypted cookie values for Go web applications, guarding session data from tampering.
Repository Health
Technical Analysis
gorilla/securecookie is a small, dependency-free Go library for signing and optionally encrypting the values stored in HTTP cookies. Every value it encodes is authenticated with HMAC, so an application can trust that a cookie it reads back on a later request has not been forged or altered in transit; supplying a block key layers AES-CTR encryption on top so the content is unreadable to the client as well.
Beyond the core Encode/Decode pair, the library ships key-rotation helpers (CodecsFromPairs, EncodeMulti, DecodeMulti) that let an application hold multiple key pairs at once, so secrets can be rotated without invalidating cookies that were signed with the previous key. It also powers the cookie store used internally by gorilla/sessions.
What You Get
- HMAC-SHA256 signed cookie encoding and decoding via SecureCookie.Encode/Decode
- Optional AES-CTR encryption layered on top of the signature via a block key
- A pluggable Serializer interface with GobEncoder, JSONEncoder, and NopEncoder included
- Multi-codec helpers (CodecsFromPairs, EncodeMulti, DecodeMulti) for zero-downtime key rotation
- A typed Error interface (IsUsage/IsDecode/IsInternal) so callers can distinguish misconfiguration from tampered or expired cookies
Common Use Cases
- Signing session identifiers for a custom Go web server or middleware
- Storing small pieces of user state directly in an encrypted cookie instead of a server-side session store
- Rotating signing and encryption keys periodically without invalidating cookies mid-rotation
- Backing the cookie store implementation used by gorilla/sessions
Under The Hood
Architecture securecookie is a single flat package built around one exported type, SecureCookie, plus the standalone functions and interfaces needed to compose it. Encode() and Decode() in securecookie.go implement a linear pipeline: serialize via the pluggable Serializer (GobEncoder, JSONEncoder, or NopEncoder), optionally run the value through AES-CTR encryption (encrypt/decrypt), base64-encode it, then sign the name|timestamp|value tuple with HMAC (createMac/verifyMac) and base64-encode the whole thing again; Decode() reverses each step and additionally enforces MaxAge/MinAge timestamp bounds. Configuration is chainable (MaxLength, MaxAge, MinAge, HashFunc, BlockFunc, SetSerializer all return *SecureCookie), and the small Codec interface plus CodecsFromPairs/EncodeMulti/DecodeMulti is the library’s only extension point, letting callers hold several key pairs for rotation. Because everything funnels through this one struct and interface, the abstraction that would ripple if changed is the Encode/Decode wire format itself, which the maintainers treat as effectively frozen given the project’s maturity.
Tech Stack The library depends on nothing beyond the Go standard library at runtime — crypto/aes, crypto/cipher, crypto/hmac, crypto/sha256, crypto/subtle, crypto/rand, encoding/base64, encoding/gob, and encoding/json cover encryption, hashing, constant-time comparison, and serialization; the only declared module dependency, github.com/google/gofuzz, is test-only, used by the native Go fuzz test. go.mod targets Go 1.20. There is no web-framework coupling — the package operates purely on strings and byte slices, so it plugs into net/http, gorilla/mux, gorilla/sessions, or any other Go HTTP stack equally. CI (GitHub Actions) runs the test suite across Go 1.20/1.21 on Linux, macOS, and Windows, plus separate GolangCI-Lint, GoSec, and govulncheck workflows.
Code Quality Testing lives in securecookie_test.go and is substantial for the package’s size: table-driven tests cover round-trip encode/decode, wrong-key decode failures, invalid base64 input, MAC verification, AES encryption, all three serializers, multi-error aggregation, and missing-key handling, plus a native Go fuzz test (FuzzEncodeDecode) seeded via github.com/google/gofuzz that exercises encode/decode against a large corpus of generated values. Tests run with -race and coverage in CI. Error handling is explicit and typed rather than swallowed: every failure path returns a cookieError implementing a custom Error interface with IsUsage/IsDecode/IsInternal classification, and MultiError aggregates failures across rotated codecs. Naming is consistent and idiomatic Go, every exported symbol carries a godoc comment, and the project runs golangci-lint, gosec, and govulncheck in CI on every push.
API Design The public surface is deliberately minimal: New(hashKey, blockKey) constructs a codec in one line, and Encode/Decode are the only two methods most callers ever touch, with optional chainable configuration (MaxAge, MaxLength, HashFunc, BlockFunc, SetSerializer) for the rest. Getting started requires no setup beyond generating two byte slices with GenerateRandomKey(), and the godoc and README examples map directly onto net/http.Cookie usage. The design doesn’t introduce anything novel cryptographically — it’s the well-established sign-then-optionally-encrypt cookie pattern also used internally by other frameworks’ cookie stores — but its key-rotation primitives (CodecsFromPairs/EncodeMulti/DecodeMulti) are a genuinely useful, uncommon convenience that many comparable libraries omit, letting an application rotate secrets without forcing every user to re-authenticate.
Used by 7 apps in this directory
authentik
Authentication · Security
The self-hosted Identity Provider that replaces Okta, Auth0, and Entra ID with a unified SSO platform supporting SAML, OAuth2/OIDC, LDAP, RADIUS, and WebAuthn.
Hatchet
AI Development · Developer Tools · Automation
A Postgres-backed orchestration engine for background tasks, AI agents, and durable workflows that replaces Redis queues and multi-datastore durable execution platforms with a single self-hostable service.
Ory Kratos
Authentication
API-first identity and user management that handles login, registration, MFA, and recovery so your application never has to.
Rill
Analytics · Data Engineering
The fastest BI tool for humans and agents — define metrics, models, and dashboards as code and query them instantly on ClickHouse or DuckDB.
seonaut
Marketing · Developer Tools
Self-hosted SEO auditing that crawls your entire website and surfaces critical issues — broken links, duplicate meta tags, redirect loops, and more — before they hurt your rankings.
Wakapi
Developer Tools · Analytics
Self-hosted WakaTime-compatible coding statistics backend that gives developers full control over their coding activity data.
ZITADEL
Authentication
Open-source, API-first identity platform delivering multi-tenancy, Passkeys, OIDC, SAML, and SCIM without vendor lock-in.