-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature_verifier.go
69 lines (53 loc) · 1.71 KB
/
signature_verifier.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package sofortpay
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
"strings"
"github.com/pkg/errors"
)
// To ensure the authenticity and integrity of the payload of a webhook, we sign the payload with a shared secret.
// The signature is transmitted in a header with our request and is named X-Payload-Signature. The header has the following structure:
// X-Payload-Signature: v1=<v1_signature_hash>;
type SignatureVerifier interface {
Verify(xPayloadSignature string, webHookPayload []byte) error
}
var versionToAlgorithmsMap = map[string]string{
"v1": "sha256",
}
type signatureVerifier struct {
sharedSecret string
}
// Verify signature using shared secret
func (rcv *signatureVerifier) Verify(xPayloadSignature string, webHookPayload []byte) error {
for _, versionedSignature := range strings.Split(xPayloadSignature, ";") {
var version, signature string
idx := strings.IndexByte(versionedSignature, '=')
if idx == -1 {
return errors.New("sofort pay: invalid signature (separator not found)")
}
version = versionedSignature[:idx]
adjustedPos := idx + 1
if adjustedPos >= len(versionedSignature) {
return errors.New("sofort pay: invalid signature")
}
signature = versionedSignature[adjustedPos:]
sum, err := rcv.hashSumByVersion(version, webHookPayload)
if err != nil {
return err
}
if fmt.Sprintf("%x", sum) == signature {
return nil
}
}
return errors.New("sofort pay: invalid signature")
}
func (rcv *signatureVerifier) hashSumByVersion(version string, webHookPayload []byte) ([]byte, error) {
switch version {
case "v1":
h := hmac.New(sha256.New, []byte(rcv.sharedSecret))
h.Write(webHookPayload)
return h.Sum(nil), nil
}
return nil, errors.New("sofort pay: hashing error")
}