securecookie encodes and decodes authenticated and optionally encrypted cookie values.

译文:securecookie对经过身份验证和可选加密的cookie值进行编码和解码。

文档

安装

go get github.com/gorilla/securecookie

示例

加密

package main

import (
"fmt"

"github.com/gorilla/securecookie"
)

func main() {
// Hash keys should be at least 32 bytes long
var hashKey = []byte("secret")

// 实例化 securecookie
var secure = securecookie.New(hashKey, nil)

name := "userid"
value := "1234567"

// 对value进行编码
encodeValue, _ := secure.Encode(name, value)
fmt.Printf("encodeValue: %v\n", encodeValue)
// MTY2NzM1MjIxNXxDZ3dBQnpFeU16UTFOamM9fHtnTTKIl3ZkYrr4_8w8zpdtyCkeDNmgXi7JsVIhmw5f
}

解密

package main

import (
"fmt"

"github.com/gorilla/securecookie"
)

func main() {
// Hash keys should be at least 32 bytes long
var hashKey = []byte("secret")

// 实例化 securecookie
var secure = securecookie.New(hashKey, nil)

name := "userid"

// 对value进行编码
encodeValue := "MTY2NzM1MjIxNXxDZ3dBQnpFeU16UTFOamM9fHtnTTKIl3ZkYrr4_8w8zpdtyCkeDNmgXi7JsVIhmw5f"

value := ""
secure.Decode(name, encodeValue, &value)
fmt.Printf("value: %v\n", value)
// value: 1234567
}

参考 ​​「Go工具箱」web中想让cookie值更安全?推荐使用securecookie包​