You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

98 lines
3.1 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using LitJson;
namespace Sog.Crypto
{
public static class HeroUSDKSecurity
{
public static MD5 _md5 = MD5.Create();
// 生成http请求中的data字段
public static string CreateData(Dictionary<string, string> dataParam)
{
JsonData data = new JsonData();
foreach (KeyValuePair<string, string> pair in dataParam)
{
data[pair.Key] = new JsonData(pair.Value);
}
string jsonStr = data.ToJson();
string finalData = Convert.ToBase64String(Encoding.ASCII.GetBytes(jsonStr));
if (finalData.Length > 51)
{
char[] array = finalData.ToCharArray();
SwapChar(array, 1, 33);
SwapChar(array, 10, 42);
SwapChar(array, 18, 50);
SwapChar(array, 19, 51);
finalData = new string(array);
}
return finalData;
}
// 传入按字母排序后的请求参数, 不包含_appKey, 返回签名
public static string CalcSign(string appKey, Dictionary<string, string> allParam)
{
var str = CreateParamsStr(appKey, allParam, true);
byte[] md5Hash = _md5.ComputeHash(Encoding.UTF8.GetBytes(str));
string md5Str = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
//if (md5Str.Length > 23)
//{
// char[] array = md5Str.ToCharArray();
// SwapChar(array, 1, 13);
// SwapChar(array, 5, 17);
// SwapChar(array, 7, 23);
// md5Str = new string(array);
//}
TraceLog.Trace("HeroUSDKSecurity.CalcSign str {0}, md5 {1}", str, md5Str);
return md5Str;
}
private static void SwapChar(char[] str, int idx1, int idx2)
{
if (idx1 >= 0 && idx2 >= 0 && str.Length > Math.Max(idx1, idx2))
{
char tmp = str[idx1];
str[idx1] = str[idx2];
str[idx2] = tmp;
}
}
private static string CreateParamsStr(string appKey, Dictionary<string, string> allParam, bool sortParam)
{
// sign不参与签名
allParam.Remove("sign");
StringBuilder sb = new StringBuilder();
// 生成签名串, "k1=v1&k2=v2...&_appKey"
if (sortParam)
{
var sortPairs = from pair in allParam orderby pair.Key select pair;
foreach (KeyValuePair<string, string> pair in sortPairs)
{
sb.Append(pair.Key).Append('=').Append(pair.Value).Append('&');
}
}
else
{
foreach (KeyValuePair<string, string> pair in allParam)
{
sb.Append(pair.Key).Append('=').Append(pair.Value).Append('&');
}
}
sb.Append(appKey);
return sb.ToString();
}
}
}