Skip to content

Commit 8a27d76

Browse files
authored
Make hash function in signature settable (#299)
1 parent c1259a7 commit 8a27d76

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

Diff for: protocol/auth/sign/sign.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"crypto/sha1"
2323
"encoding/base64"
2424
"fmt"
25+
"hash"
2526
"net/url"
2627
"strconv"
2728
"time"
@@ -37,6 +38,17 @@ const (
3738
question = "?"
3839
)
3940

41+
var (
42+
h = sha1.New
43+
)
44+
45+
// SetHash set hash function
46+
func SetHash(f func() hash.Hash) func() hash.Hash {
47+
o := h
48+
h = f
49+
return o
50+
}
51+
4052
// AuthSignature apollo 授权
4153
type AuthSignature struct {
4254
}
@@ -63,7 +75,7 @@ func (t *AuthSignature) HTTPHeaders(url string, appID string, secret string) map
6375

6476
func signString(stringToSign string, accessKeySecret string) string {
6577
key := []byte(accessKeySecret)
66-
mac := hmac.New(sha1.New, key)
78+
mac := hmac.New(h, key)
6779
mac.Write([]byte(stringToSign))
6880
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
6981
}

Diff for: protocol/auth/sign/sign_test.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
1818
package sign
1919

2020
import (
21-
. "github.com/tevid/gohamcrest"
21+
"crypto/sha256"
2222
"testing"
23+
24+
. "github.com/tevid/gohamcrest"
2325
)
2426

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

38+
func TestSetHash(t *testing.T) {
39+
o := SetHash(sha256.New)
40+
defer func() { SetHash(o) }()
41+
s := signString(rawURL, secret)
42+
Assert(t, s, Equal("XeIN8X6lAoujl6i88icVreaMYlBXeDco348545DkQDY="))
43+
}
44+
3645
func TestUrl2PathWithQuery(t *testing.T) {
3746

3847
pathWithQuery := url2PathWithQuery(rawURL)

0 commit comments

Comments
 (0)