58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
|
|
package fadada
|
||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/hmac"
|
||
|
|
"crypto/sha256"
|
||
|
|
"encoding/hex"
|
||
|
|
"sort"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
const (
|
||
|
|
signTypeHMACSHA256 = "HMAC-SHA256"
|
||
|
|
apiSubVersion = "5.1"
|
||
|
|
)
|
||
|
|
|
||
|
|
// SignByMap 法大大 HMAC-SHA256 签名(与官方 SDK 算法一致)
|
||
|
|
// 1) 对 map key 字典序排序,拼接 key=value&...(跳过空值)
|
||
|
|
// 2) signText = hex(SHA256(signContent))
|
||
|
|
// 3) signKey = HMAC-SHA256(timestamp, appSecret) 原始字节
|
||
|
|
// 4) signature = lowercase(hex(HMAC-SHA256(signText, signKey)))
|
||
|
|
func SignByMap(headMap map[string]string, timestamp, appSecret string) string {
|
||
|
|
signContent := sortMapForSign(headMap)
|
||
|
|
signText := sha256Hex(signContent)
|
||
|
|
secretSigning := hmacSHA256Bytes(timestamp, []byte(appSecret))
|
||
|
|
return strings.ToLower(hmacSHA256Hex(signText, secretSigning))
|
||
|
|
}
|
||
|
|
|
||
|
|
func sortMapForSign(headMap map[string]string) string {
|
||
|
|
keys := make([]string, 0, len(headMap))
|
||
|
|
for k := range headMap {
|
||
|
|
keys = append(keys, k)
|
||
|
|
}
|
||
|
|
sort.Strings(keys)
|
||
|
|
|
||
|
|
parts := make([]string, 0, len(keys))
|
||
|
|
for _, k := range keys {
|
||
|
|
if v := headMap[k]; v != "" {
|
||
|
|
parts = append(parts, k+"="+v)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return strings.Join(parts, "&")
|
||
|
|
}
|
||
|
|
|
||
|
|
func sha256Hex(src string) string {
|
||
|
|
sum := sha256.Sum256([]byte(src))
|
||
|
|
return hex.EncodeToString(sum[:])
|
||
|
|
}
|
||
|
|
|
||
|
|
func hmacSHA256Bytes(data string, secret []byte) []byte {
|
||
|
|
h := hmac.New(sha256.New, secret)
|
||
|
|
h.Write([]byte(data))
|
||
|
|
return h.Sum(nil)
|
||
|
|
}
|
||
|
|
|
||
|
|
func hmacSHA256Hex(data string, secret []byte) string {
|
||
|
|
return hex.EncodeToString(hmacSHA256Bytes(data, secret))
|
||
|
|
}
|