2014-10-03 124 views
3

当我创建新的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, 
     }, 
    } 
} 

我认为传递正确的参数。

回答

6

从您链接的文档:

//这是推荐使用的认证密钥具有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作出评论很有道理的,所以牢记:

另请注意,重新启动应用程序意味着它在使用此方法时无法读取现有会话(因为每次生成新密钥)。

+4

另请注意,重新启动应用程序意味着它在使用此方法时无法读取现有会话(因为每次生成新密钥)。 – elithrar 2014-10-04 00:00:23