From a768bf8f00030e627f4546b421f9242b0de56c01 Mon Sep 17 00:00:00 2001 From: wang yan Date: Thu, 6 Feb 2020 17:26:04 +0800 Subject: [PATCH] update hash algorithm for signing the cookie for xsrf token Due to the chosen-prefix collision in SHA-1(details at https://sha-mbles.github.io/), SHA-1 hash functions should to be deprecated and SHA-2/SHA-3 should be used instead. Signed-off-by: wang yan --- context/context.go | 6 +++--- session/sess_utils.go | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/context/context.go b/context/context.go index e1262018..de248ed2 100644 --- a/context/context.go +++ b/context/context.go @@ -25,7 +25,7 @@ package context import ( "bufio" "crypto/hmac" - "crypto/sha1" + "crypto/sha256" "encoding/base64" "errors" "fmt" @@ -123,7 +123,7 @@ func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) { timestamp := parts[1] sig := parts[2] - h := hmac.New(sha1.New, []byte(Secret)) + h := hmac.New(sha256.New, []byte(Secret)) fmt.Fprintf(h, "%s%s", vs, timestamp) if fmt.Sprintf("%02x", h.Sum(nil)) != sig { @@ -137,7 +137,7 @@ func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) { func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) { vs := base64.URLEncoding.EncodeToString([]byte(value)) timestamp := strconv.FormatInt(time.Now().UnixNano(), 10) - h := hmac.New(sha1.New, []byte(Secret)) + h := hmac.New(sha256.New, []byte(Secret)) fmt.Fprintf(h, "%s%s", vs, timestamp) sig := fmt.Sprintf("%02x", h.Sum(nil)) cookie := strings.Join([]string{vs, timestamp, sig}, "|") diff --git a/session/sess_utils.go b/session/sess_utils.go index 2e3376c7..20915bb6 100644 --- a/session/sess_utils.go +++ b/session/sess_utils.go @@ -19,7 +19,7 @@ import ( "crypto/cipher" "crypto/hmac" "crypto/rand" - "crypto/sha1" + "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/gob" @@ -129,7 +129,7 @@ func encodeCookie(block cipher.Block, hashKey, name string, value map[interface{ b = encode(b) // 3. Create MAC for "name|date|value". Extra pipe to be used later. b = []byte(fmt.Sprintf("%s|%d|%s|", name, time.Now().UTC().Unix(), b)) - h := hmac.New(sha1.New, []byte(hashKey)) + h := hmac.New(sha256.New, []byte(hashKey)) h.Write(b) sig := h.Sum(nil) // Append mac, remove name. @@ -153,7 +153,7 @@ func decodeCookie(block cipher.Block, hashKey, name, value string, gcmaxlifetime } b = append([]byte(name+"|"), b[:len(b)-len(parts[2])]...) - h := hmac.New(sha1.New, []byte(hashKey)) + h := hmac.New(sha256.New, []byte(hashKey)) h.Write(b) sig := h.Sum(nil) if len(sig) != len(parts[2]) || subtle.ConstantTimeCompare(sig, parts[2]) != 1 {