Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gorilla session invalid key size

Tags:

go

When I create new cookie store and do like:

var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(1), securecookie.GenerateRandomKey(2))

I've got the the error message

crypto/aes: invalid key size 2

Why what do I wrong? When I look at the function definition

// NewCookieStore returns a new CookieStore.
//
// Keys are defined in pairs to allow key rotation, but the common case is
// to set a single authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for
// encryption. The encryption key can be set to nil or omitted in the last
// pair, but the authentication key is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes.
// The encryption key, if set, must be either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256 modes.
//
// Use the convenience function securecookie.GenerateRandomKey() to create
// strong keys.
func NewCookieStore(keyPairs ...[]byte) *CookieStore {
    return &CookieStore{
        Codecs: securecookie.CodecsFromPairs(keyPairs...),
        Options: &Options{
            Path:   "/",
            MaxAge: 86400 * 30,
        },
    }
}

I think pass the right parameter.

like image 919
softshipper Avatar asked Feb 12 '23 21:02

softshipper


1 Answers

From the documentation you linked:

// It is recommended to use an authentication key with 32 or 64 bytes.

// The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.

So you could use something like this:

//replace 16 with 24 for 192bit or 32 for 256bit.
var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(16), 
                                    securecookie.GenerateRandomKey(16))

// edit

Also @elithrar made a very valid point in comments, so keep it in mind:

Also note that restarting your application means that it cannot read existing sessions (as new keys are generated every time) when using this method.

like image 110
OneOfOne Avatar answered Mar 12 '23 00:03

OneOfOne