Files
flatrender/services/payment/internal/signing/signing.go
T

30 lines
942 B
Go
Raw Normal View History

// Package signing provides the HMAC-SHA256 helpers the broker uses to (a) verify
// inbound client requests and (b) sign outbound webhooks + return redirects so a
// client site can trust a result came from the broker untampered.
package signing
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
// Sign returns the lowercase hex HMAC-SHA256 of message keyed by secret.
func Sign(secret string, message []byte) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(message)
return hex.EncodeToString(mac.Sum(nil))
}
// Verify compares an expected hex signature against the computed one in constant time.
func Verify(secret string, message []byte, provided string) bool {
expected := Sign(secret, message)
// hmac.Equal is constant-time; compare the raw bytes after decoding.
pb, err := hex.DecodeString(provided)
if err != nil {
return false
}
eb, _ := hex.DecodeString(expected)
return hmac.Equal(eb, pb)
}