37 lines
615 B
Go
37 lines
615 B
Go
package crypto
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
)
|
|
|
|
// HMACSigner HMAC签名器
|
|
type HMACSigner struct {
|
|
key []byte
|
|
}
|
|
|
|
// NewHMACSigner 创建HMAC签名器
|
|
func NewHMACSigner(key string) *HMACSigner {
|
|
return &HMACSigner{key: []byte(key)}
|
|
}
|
|
|
|
func (s *HMACSigner) Sign(data []byte) ([]byte, error) {
|
|
h := hmac.New(sha256.New, s.key)
|
|
h.Write(data)
|
|
return h.Sum(nil), nil
|
|
}
|
|
|
|
func (s *HMACSigner) Verify(data, signature []byte) error {
|
|
expected, err := s.Sign(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !hmac.Equal(expected, signature) {
|
|
return fmt.Errorf("签名验证失败")
|
|
}
|
|
|
|
return nil
|
|
}
|