[🚀] add crypto pkg
This commit is contained in:
36
pkg/crypto/hmac.go
Normal file
36
pkg/crypto/hmac.go
Normal file
@@ -0,0 +1,36 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user