forked from braintree-go/braintree-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhmac.go
50 lines (43 loc) · 934 Bytes
/
hmac.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package braintree
import (
"crypto/hmac"
"crypto/sha1"
"errors"
"fmt"
"io"
)
type SignatureError struct {
message string
}
func (i SignatureError) Error() string {
if i.message == "" {
return "Invalid Signature"
}
return i.message
}
func newHmacer(bt *Braintree) hmacer {
return hmacer{bt}
}
type hmacer struct {
*Braintree
}
func (h hmacer) verifySignature(signature, payload string) (bool, error) {
expectedSignature, err := h.hmac(payload)
if err != nil {
return false, err
}
return hmac.Equal([]byte(expectedSignature), []byte(signature)), nil
}
func (h hmacer) hmac(payload string) (string, error) {
s := sha1.New()
_, err := io.WriteString(s, h.PrivateKey)
if err != nil {
return "", errors.New("Could not write private key to SHA1")
}
mac := hmac.New(sha1.New, s.Sum(nil))
_, err = mac.Write([]byte(payload))
if err != nil {
return "", err
}
return fmt.Sprintf("%x", mac.Sum(nil)), nil
}