transfer_yl/untils/sign/sign.go

67 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-07-16 16:51:39 +08:00
package sign
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/spf13/cast"
"sort"
)
var filterKeys = []string{"sign", "extendParams", "msg"}
func GetSign(data map[string]interface{}, primary string) (string, error) {
filterData(&data)
sysSign, err := hash256AndBase64(sortValue(data, primary))
if err != nil {
return "", fmt.Errorf("参数加密失败")
}
return sysSign, nil
}
func filterData(data *map[string]interface{}) {
for _, key := range filterKeys {
delete(*data, key)
}
}
func sortValue(data map[string]interface{}, primary string) string {
var sortValueString string
data["key"] = primary
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
// 对键进行排序
sort.Strings(keys)
// 按照排序后的键的顺序输出map的值
for _, v := range keys {
sortValueString += cast.ToString(data[v])
}
return sortValueString
}
func hash256AndBase64(valueString string) (string, error) {
// 创建一个新的hash.Hash计算器并指定算法为sha256
hasher := sha256.New()
// 写入数据到hash计算器
hasher.Write([]byte(valueString))
// Sum方法返回计算出的哈希值的字节切片
hashBytes := hasher.Sum(nil)
//将字符串编码为16进制格式,返回字符串
hashCode := hex.EncodeToString(hashBytes)
// 将哈希值的字节切片编码为Base64字符串
hashBase64 := base64.StdEncoding.EncodeToString([]byte(hashCode))
return hashBase64, nil
}