Skip to content

Commit c3a6c77

Browse files
committed
Merge pull request #3 from pusher/hmac_equals
Webhook validation uses hmac.Equals instead of ==
2 parents 1948a8f + 47ff8bd commit c3a6c77

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

client.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ If it is invalid, the first return value will be nil, and an error will be passe
395395
func (c *Client) Webhook(header http.Header, body []byte) (*Webhook, error) {
396396

397397
for _, token := range header["X-Pusher-Key"] {
398-
if token == c.Key && checkSignature(header.Get("X-Pusher-Signature"), string(body), c.Secret) {
398+
if token == c.Key && checkSignature(header.Get("X-Pusher-Signature"), c.Secret, body) {
399399
return unmarshalledWebhook(body)
400400
}
401401
}

crypto.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,28 @@ import (
55
"crypto/md5"
66
"crypto/sha256"
77
"encoding/hex"
8+
// "fmt"
89
"strings"
910
)
1011

1112
func hmacSignature(toSign, secret string) string {
12-
_authSignature := hmac.New(sha256.New, []byte(secret))
13-
_authSignature.Write([]byte(toSign))
14-
return hex.EncodeToString(_authSignature.Sum(nil))
13+
return hex.EncodeToString(hmacBytes([]byte(toSign), []byte(secret)))
1514
}
1615

17-
func checkSignature(result, body, secret string) bool {
18-
expected := hmacSignature(body, secret)
19-
return result == expected
16+
func hmacBytes(toSign, secret []byte) []byte {
17+
_authSignature := hmac.New(sha256.New, secret)
18+
_authSignature.Write(toSign)
19+
return _authSignature.Sum(nil)
20+
}
21+
22+
func checkSignature(result, secret string, body []byte) bool {
23+
expected := hmacBytes(body, []byte(secret))
24+
resultBytes, err := hex.DecodeString(result)
25+
26+
if err != nil {
27+
return false
28+
}
29+
return hmac.Equal(expected, resultBytes)
2030
}
2131

2232
func createAuthMap(key, secret, stringToSign string) map[string]string {

0 commit comments

Comments
 (0)