【问题标题】:Decrypting Gorilla Sessions Cookie Data解密 Gorilla 会话 Cookie 数据
【发布时间】:2016-09-26 05:11:57
【问题描述】:

首先,让我先说我正在参加夺旗比赛,但我在回答与 Go Gorilla Sessions 相关的问题时遇到了一些困难。我从来没有用 Go 写过代码,所以这很有趣,也很令人沮丧:)

我有一个密钥。我有一个编码的 Cookie。我需要使用我拥有的密钥对 cookie 进行解码,编辑其中的任何数据,并使用我更改的数据重新加密以在挑战中取得进展。

我已经阅读了 Gorilla Sessions Package 文档并没有真正得到任何帮助。

谁能帮忙,我从哪里开始?

【问题讨论】:

  • 您是否查看过 Gorilla 会话使用的 securecookie 库中的 Codec 实现? github.com/gorilla/securecookie/blob/master/securecookie.go
  • 谢谢,但最初我忽略了它,因为挑战的提示告诉我要查看 Gorilla Sessions 而不是 SecureCookie。不过使用那个包是有意义的,所以感谢分享!

标签: go gorilla


【解决方案1】:

查看文档 - gorilla 提供了 secure cookie package。 根据您的应用架构 - 基本实现可以按如下方式工作:

创建一个供您的应用使用的会话管理包。举个例子 - 让我们称之为sessionmngr

sessionmngr 内部,导入"github.com/gorilla/securecookie"

sessionmngr 包中,使用小写的init() 函数来设置securecookie 的私有实例。导入包后,将按照声明的顺序调用小写的 init() 函数。 (查看语言spec 了解更多信息)。您将使用此实例对来自标准库的http.Request 的 cookie 进行编码和解码。

import (
    "github.com/gorilla/securecookie"      

    //you will need this later
    "http" 
)

//declare private secure cookie 
var s *securecookie.SecureCookie

//initialize it here (taken from the gorilla docs example)
func init() {
    var hashKey = []byte("very-secret")
    var blockKey = []byte("a-lot-secret")
    s = securecookie.New(hashKey, blockKey)
}

然后,您将在需要对 cookie 的值进行编码和解码的函数中的整个包中使用 ssecurecookie package documentation 提供了一个样板示例。

为了满足读取和修改已加密 cookie 的要求 - 在上面示例中设置的 securecookie 实例上使用 DecodeEncode 方法。

有点像 ---

func DecodeAndModify(w http.ResponseWriter, r *http.Request) {
    //get reference to cookie if set
    if cookie, err := r.Cookie("cookie-name"); err == nil {

        value := make(map[string]string)
        //use Decode to get the value from the cookie
        if err = s.Decode("cookie-name", cookie.Value, &value); err == nil {
            //modify the value in some way
            value["newKey"] = "newValue"
            //re-encode it
            if encoded, err := s.Encode("cookie-name", value); err == nil {
                cookie := &http.Cookie{
                    Name:  "cookie-name",
                    Value: encoded,
                    Path:  "/",
                }
                http.SetCookie(w, cookie)
            }
        }
    }
}

【讨论】:

  • 感谢 Syllabix,感谢详细的回答。我相信这正是我所需要的,因此将答案标记为正确,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2017-05-19
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
相关资源
最近更新 更多