-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsignature.go
48 lines (39 loc) · 1.14 KB
/
signature.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
package eventsub_framework
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"strings"
)
type signatureVerifyError struct {
Message string
}
func (s *signatureVerifyError) Error() string {
return s.Message
}
func VerifyRequestSignature(req *http.Request, body, secret []byte) (bool, error) {
signatureValue := req.Header.Get("Twitch-Eventsub-Message-Signature")
if signatureValue == "" {
return false, &signatureVerifyError{"missing signature header"}
}
signatureBytes, err := getHmacBytes(signatureValue)
if err != nil {
return false, &signatureVerifyError{"invalid signature format"}
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(req.Header.Get("Twitch-Eventsub-Message-Id")))
mac.Write([]byte(req.Header.Get("Twitch-Eventsub-Message-Timestamp")))
mac.Write(body)
outputHmac := mac.Sum(nil)
return hmac.Equal(signatureBytes, outputHmac), nil
}
func getHmacBytes(sigValue string) ([]byte, error) {
parts := strings.SplitN(sigValue, "=", 2)
if len(parts) != 2 {
return nil, errors.New("expected 2 components from signature header")
}
hexValue := parts[1]
return hex.DecodeString(hexValue)
}