Files
tyapi-server/internal/infrastructure/external/jiguang/crypto.go

48 lines
1.4 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 jiguang
import (
"crypto/hmac"
"crypto/md5"
"encoding/hex"
"fmt"
)
// SignMethod 签名方法类型
type SignMethod string
const (
SignMethodMD5 SignMethod = "md5"
SignMethodHMACMD5 SignMethod = "hmac"
)
// GenerateSign 生成签名
// 根据 signMethod 参数选择使用 MD5 或 HMAC-MD5 算法
// MD5: md5(timestamp + "&appSecret=" + appSecret),然后转大写十六进制
// HMAC-MD5: hmac_md5(timestamp, appSecret),然后转大写十六进制
func GenerateSign(timestamp string, appSecret string, signMethod SignMethod) (string, error) {
var hashBytes []byte
switch signMethod {
case SignMethodMD5:
// MD5算法在待签名字符串后面加上 &appSecret=xxx 再进行计算
signStr := timestamp + "&appSecret=" + appSecret
hash := md5.Sum([]byte(signStr))
hashBytes = hash[:]
case SignMethodHMACMD5:
// HMAC-MD5算法使用 appSecret 初始化摘要算法再进行计算
mac := hmac.New(md5.New, []byte(appSecret))
mac.Write([]byte(timestamp))
hashBytes = mac.Sum(nil)
default:
return "", fmt.Errorf("不支持的签名方法: %s", signMethod)
}
// 将二进制转化为大写的十六进制正确签名应该为32大写字符串
return hex.EncodeToString(hashBytes), nil
}
// GenerateSignWithDefault 使用默认的 HMAC-MD5 方法生成签名
func GenerateSignWithDefault(timestamp string, appSecret string) (string, error) {
return GenerateSign(timestamp, appSecret, SignMethodHMACMD5)
}