Files
hyapi-server/internal/infrastructure/external/nuoer/crypto.go
2026-06-05 14:12:48 +08:00

60 lines
1.3 KiB
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[:])
}
// MD5Encrypt 对业务入参做 MD5 加密(小写十六进制),用于 encryptionType=2。
func MD5Encrypt(plaintext string) string {
return genMD5(plaintext)
}
// encryptBodyMD5 将 body 中各非空字段值转为 MD5 密文。
func encryptBodyMD5(body map[string]string) map[string]string {
if len(body) == 0 {
return body
}
encrypted := make(map[string]string, len(body))
for k, v := range body {
if strings.TrimSpace(v) == "" {
encrypted[k] = v
continue
}
encrypted[k] = MD5Encrypt(v)
}
return encrypted
}