package securecookie

import "github.com/gorilla/securecookie"

Installation | Overview | API | Files

Installation

$ go get github.com/gorilla/securecookie

Overview

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

Secure cookies can't be forged, because their values are validated using HMAC. When encrypted, the content is also inaccessible to malicious eyes.

To use it, first create a new SecureCookie instance:

var hashKey = []byte("very-secret")
var blockKey = []byte("a-lot-secret")
var s = securecookie.New(hashKey, blockKey)

The hashKey is required, used to authenticate the cookie value using HMAC. It is recommended to use a key with 32 or 64 bytes.

The blockKey is optional, used to encrypt the cookie value -- set it to nil to not use encryption. If set, the length must correspond to the block size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

Strong keys can be created using the convenience function GenerateRandomKey().

Once a SecureCookie instance is set, use it to encode a cookie value:

func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
    value := map[string]string{
        "foo": "bar",
    }
    if encoded, err := s.Encode("cookie-name", value); err == nil {
        cookie := &http.Cookie{
            Name:  "cookie-name",
            Value: encoded,
            Path:  "/",
        }
        http.SetCookie(w, cookie)
    }
}

Later, use the same SecureCookie instance to decode and validate a cookie value:

func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
    if cookie, err := r.Cookie("cookie-name"); err == nil {
        value := make(map[string]string)
        if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
            fmt.Fprintf(w, "The value of foo is %q", value["foo"])
        }
    }
}

We stored a map[string]string, but secure cookies can hold any value that can be encoded using encoding/gob. To store custom types, they must be registered first using gob.Register(). For basic types this is not needed; it works out of the box.

API

Package Files

Variables

var (
    ErrMacInvalid = errors.New("securecookie: the value is not valid")
)

func CodecsFromPairs

func CodecsFromPairs(keyPairs ...[]byte) []Codec

CodecsFromPairs returns a slice of SecureCookie instances.

It is a convenience function to create a list of codecs for key rotation.

func DecodeMulti

func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error

DecodeMulti decodes a cookie value using a group of codecs.

The codecs are tried in order. Multiple codecs are accepted to allow key rotation.

func EncodeMulti

func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error)

EncodeMulti encodes a cookie value using a group of codecs.

The codecs are tried in order. Multiple codecs are accepted to allow key rotation.

func GenerateRandomKey

func GenerateRandomKey(strength int) []byte

GenerateRandomKey creates a random key with the given strength.

type Codec

type Codec interface {
    Encode(name string, value interface{}) (string, error)
    Decode(name, value string, dst interface{}) error
}

Codec defines an interface to encode and decode cookie values.

type MultiError

type MultiError []error

MultiError groups multiple errors.

func (MultiError) Error

func (m MultiError) Error() string

type SecureCookie

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

SecureCookie encodes and decodes authenticated and optionally encrypted cookie values.

func New

func New(hashKey, blockKey []byte) *SecureCookie

New returns a new SecureCookie.

hashKey is required, used to authenticate values using HMAC. Create it using GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes.

blockKey is optional, used to encrypt values. Create it using GenerateRandomKey(). The key length must correspond to the block size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func (*SecureCookie) BlockFunc

func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie

BlockFunc sets the encryption function used to create a cipher.Block.

Default is crypto/aes.New.

func (*SecureCookie) Decode

func (s *SecureCookie) Decode(name, value string, dst interface{}) error

Decode decodes a cookie value.

It decodes, verifies a message authentication code, optionally decrypts and finally deserializes the value.

The name argument is the cookie name. It must be the same name used when it was stored. The value argument is the encoded cookie value. The dst argument is where the cookie will be decoded. It must be a pointer.

func (*SecureCookie) Encode

func (s *SecureCookie) Encode(name string, value interface{}) (string, error)

Encode encodes a cookie value.

It serializes, optionally encrypts, signs with a message authentication code, and finally encodes the value.

The name argument is the cookie name. It is stored with the encoded value. The value argument is the value to be encoded. It can be any value that can be encoded using encoding/gob. To store special structures, they must be registered first using gob.Register().

func (*SecureCookie) HashFunc

func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie

HashFunc sets the hash function used to create HMAC.

Default is crypto/sha256.New.

func (*SecureCookie) MaxAge

func (s *SecureCookie) MaxAge(value int) *SecureCookie

MaxAge restricts the maximum age, in seconds, for the cookie value.

Default is 86400 * 30. Set it to 0 for no restriction.

func (*SecureCookie) MaxLength

func (s *SecureCookie) MaxLength(value int) *SecureCookie

MaxLength restricts the maximum length, in bytes, for the cookie value.

Default is 4096, which is the maximum value accepted by Internet Explorer.

func (*SecureCookie) MinAge

func (s *SecureCookie) MinAge(value int) *SecureCookie

MinAge restricts the minimum age, in seconds, for the cookie value.

Default is 0 (no restriction).