48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
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)
|
||
}
|