[🚀] add crypto pkg

This commit is contained in:
2026-01-21 16:40:26 +08:00
parent 424ad78a7e
commit 078967c601
5 changed files with 283 additions and 0 deletions

36
pkg/crypto/hmac.go Normal file
View 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
}