Skip to content

Commit

Permalink
Make hash function in signature settable (#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
nanjj committed Mar 27, 2024
1 parent c1259a7 commit 8a27d76
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
14 changes: 13 additions & 1 deletion protocol/auth/sign/sign.go
Expand Up @@ -22,6 +22,7 @@ import (
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"net/url"
"strconv"
"time"
Expand All @@ -37,6 +38,17 @@ const (
question = "?"
)

var (
h = sha1.New
)

// SetHash set hash function
func SetHash(f func() hash.Hash) func() hash.Hash {
o := h
h = f
return o
}

// AuthSignature apollo 鎺堟潈
type AuthSignature struct {
}
Expand All @@ -63,7 +75,7 @@ func (t *AuthSignature) HTTPHeaders(url string, appID string, secret string) map

func signString(stringToSign string, accessKeySecret string) string {
key := []byte(accessKeySecret)
mac := hmac.New(sha1.New, key)
mac := hmac.New(h, key)
mac.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
Expand Down
11 changes: 10 additions & 1 deletion protocol/auth/sign/sign_test.go
Expand Up @@ -18,8 +18,10 @@
package sign

import (
. "github.com/tevid/gohamcrest"
"crypto/sha256"
"testing"

. "github.com/tevid/gohamcrest"
)

const (
Expand All @@ -33,6 +35,13 @@ func TestSignString(t *testing.T) {
Assert(t, s, Equal("mcS95GXa7CpCjIfrbxgjKr0lRu8="))
}

func TestSetHash(t *testing.T) {
o := SetHash(sha256.New)
defer func() { SetHash(o) }()
s := signString(rawURL, secret)
Assert(t, s, Equal("XeIN8X6lAoujl6i88icVreaMYlBXeDco348545DkQDY="))
}

func TestUrl2PathWithQuery(t *testing.T) {

pathWithQuery := url2PathWithQuery(rawURL)
Expand Down

0 comments on commit 8a27d76

Please sign in to comment.