2014-10-03 128 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