Files
tyapi-server/internal/infrastructure/external/nuoer/crypto.go
2026-05-28 10:55:28 +08:00

39 lines
810 B
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 nuoer
import (
"crypto/md5"
"encoding/hex"
"sort"
"strings"
)
// Sign 根据 body 业务参数与 secret 生成 MD5 签名。
// 规则:排除空值参数,按 key 的 ASCII 升序排序,拼接「参数名+参数值」后追加 secret再 MD5小写十六进制
func Sign(body map[string]string, secret string) string {
if len(body) == 0 {
return genMD5(secret)
}
keys := make([]string, 0, len(body))
for k, v := range body {
if strings.TrimSpace(v) == "" {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var sb strings.Builder
for _, k := range keys {
sb.WriteString(k)
sb.WriteString(body[k])
}
sb.WriteString(secret)
return genMD5(sb.String())
}
func genMD5(s string) string {
sum := md5.Sum([]byte(s))
return hex.EncodeToString(sum[:])
}