-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhmac.go
More file actions
38 lines (32 loc) · 840 Bytes
/
Copy pathhmac.go
File metadata and controls
38 lines (32 loc) · 840 Bytes
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
package deploy
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"strings"
)
type HMACValidator struct {
secret []byte
}
func NewHMACValidator(secret string) *HMACValidator {
return &HMACValidator{secret: []byte(secret)}
}
func (v *HMACValidator) ValidateRequest(payload []byte, signature string) error {
if !strings.HasPrefix(signature, "sha256=") {
return fmt.Errorf("invalid signature format")
}
providedSig := strings.TrimPrefix(signature, "sha256=")
providedBytes, err := hex.DecodeString(providedSig)
if err != nil {
return fmt.Errorf("invalid hex signature: %w", err)
}
mac := hmac.New(sha256.New, v.secret)
mac.Write(payload)
expectedMAC := mac.Sum(nil)
if subtle.ConstantTimeCompare(providedBytes, expectedMAC) != 1 {
return fmt.Errorf("signature mismatch")
}
return nil
}