47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package spark
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/md5"
|
|
"crypto/sha1"
|
|
"encoding/base64"
|
|
"strconv"
|
|
)
|
|
|
|
// spark 接口签名计算
|
|
// MD5_TABLE 定义 MD5 转换表
|
|
var MD5_TABLE = []rune{
|
|
'0', '1', '2', '3', '4', '5', '6', '7',
|
|
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
|
|
}
|
|
|
|
// ApiAuthAlgorithm 定义 API 认证算法结构体
|
|
type ApiAuthAlgorithm struct{}
|
|
|
|
// GetSignature 获取签名
|
|
func (a *ApiAuthAlgorithm) GetSignature(appId, secret string, ts int64) string {
|
|
auth := a.md5(appId + strconv.FormatInt(ts, 10))
|
|
if auth == "" {
|
|
return ""
|
|
}
|
|
return a.hmacSHA1Encrypt(auth, secret)
|
|
}
|
|
|
|
// hmacSHA1Encrypt sha1 加密
|
|
func (a *ApiAuthAlgorithm) hmacSHA1Encrypt(encryptText, encryptKey string) string {
|
|
h := hmac.New(sha1.New, []byte(encryptKey))
|
|
h.Write([]byte(encryptText))
|
|
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
// md5 MD5 加密
|
|
func (a *ApiAuthAlgorithm) md5(cipherText string) string {
|
|
hash := md5.Sum([]byte(cipherText))
|
|
result := make([]rune, 32)
|
|
for i, v := range hash {
|
|
result[i*2] = MD5_TABLE[v>>4&0xf]
|
|
result[i*2+1] = MD5_TABLE[v&0xf]
|
|
}
|
|
return string(result)
|
|
}
|