57 lines
1.6 KiB
C#
57 lines
1.6 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using UnityEngine;
|
||
|
||
public class SignHelper
|
||
{
|
||
/// <summary>
|
||
/// 生成 sign
|
||
/// </summary>
|
||
/// <param name="parameters">请求参数字典(包含所有参数,但要去掉 sign)</param>
|
||
/// <param name="secret">AppSecret</param>
|
||
/// <returns>MD5 sign</returns>
|
||
public static string GetSign(Dictionary<string, object> parameters, string secret)
|
||
{
|
||
// 1. 移除 sign
|
||
if (parameters.ContainsKey("sign"))
|
||
{
|
||
parameters.Remove("sign");
|
||
}
|
||
|
||
// 2. 按照 key ASCII 排序
|
||
var sorted = parameters.OrderBy(p => p.Key, StringComparer.Ordinal);
|
||
|
||
// 3. 拼接成字符串 key+value
|
||
StringBuilder sb = new StringBuilder();
|
||
foreach (var kv in sorted)
|
||
{
|
||
string valueStr;
|
||
if (kv.Value is Array || kv.Value is List<object>)
|
||
{
|
||
// 数组需要转成 JSON 字符串
|
||
valueStr = JsonUtility.ToJson(kv.Value);
|
||
}
|
||
else
|
||
{
|
||
valueStr = kv.Value.ToString();
|
||
}
|
||
sb.Append(kv.Key).Append(valueStr);
|
||
}
|
||
|
||
// 4. 拼接 secret
|
||
sb.Append(secret);
|
||
|
||
// 5. 做 MD5 加密
|
||
using (MD5 md5 = MD5.Create())
|
||
{
|
||
byte[] inputBytes = Encoding.UTF8.GetBytes(sb.ToString());
|
||
byte[] hashBytes = md5.ComputeHash(inputBytes);
|
||
|
||
// 转换成 32 位小写 hex
|
||
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
|
||
}
|
||
}
|
||
} |