当我创建新的cookie商店并且喜欢:
var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(1), securecookie.GenerateRandomKey(2))
我收到了错误消息
crypto/aes: invalid key size 2
为什么我错了?当我查看函数定义
时// 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,
},
}
}
我认为传递正确的参数。
答案 0 :(得分:8)
来自您关联的文档:
//建议使用32或64字节的身份验证密钥。
//加密密钥(如果已设置)必须为16,24或32 字节才能选择AES-128,AES-192或AES-256模式。
所以你可以使用这样的东西:
//replace 16 with 24 for 192bit or 32 for 256bit.
var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(16),
securecookie.GenerateRandomKey(16))
//编辑
@elithrar在评论中提出了非常有效的观点,所以请记住:
另请注意,重新启动应用程序意味着在使用此方法时无法读取现有会话(因为每次都会生成新密钥)。