Files
tyapi-server/internal/infrastructure/external/shujubao/crypto.go
2026-01-30 18:25:30 +08:00

48 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package shujubao
import (
"crypto/hmac"
"crypto/md5"
"encoding/hex"
"strings"
)
// SignMethod 签名方法
type SignMethod string
const (
SignMethodMD5 SignMethod = "md5"
SignMethodHMACMD5 SignMethod = "hmac"
)
// GenerateSignMD5 使用 MD5 生成签名md5(app_secret + timestamp)32 位小写
func GenerateSignMD5(appSecret, timestamp string) string {
h := md5.Sum([]byte(appSecret + timestamp))
sign := strings.ToLower(hex.EncodeToString(h[:]))
return sign
}
// GenerateSignHMAC 使用 HMAC-MD5 生成签名(仅 timestamp兼容旧逻辑
func GenerateSignHMAC(appSecret, timestamp string) string {
mac := hmac.New(md5.New, []byte(appSecret))
mac.Write([]byte(timestamp))
sign := strings.ToLower(hex.EncodeToString(mac.Sum(nil)))
return sign
}
// GenerateSignFromParamsMD5 根据入参生成签名:入参按 ASCII 排序组合后与 app_secret 做 MD5。
// sortedParamStr 格式为 key1=value1&key2=value2&...key 按字母序)。
func GenerateSignFromParamsMD5(appSecret, sortedParamStr string) string {
h := md5.Sum([]byte(appSecret + sortedParamStr))
sign := strings.ToLower(hex.EncodeToString(h[:]))
return sign
}
// GenerateSignFromParamsHMAC 根据入参生成签名:入参按 ASCII 排序组合后与 app_secret 做 HMAC-MD5。
func GenerateSignFromParamsHMAC(appSecret, sortedParamStr string) string {
mac := hmac.New(md5.New, []byte(appSecret))
mac.Write([]byte(sortedParamStr))
sign := strings.ToLower(hex.EncodeToString(mac.Sum(nil)))
return sign
}