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 dataParam) { JsonData data = new JsonData(); foreach (KeyValuePair 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 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 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 pair in sortPairs) { sb.Append(pair.Key).Append('=').Append(pair.Value).Append('&'); } } else { foreach (KeyValuePair pair in allParam) { sb.Append(pair.Key).Append('=').Append(pair.Value).Append('&'); } } sb.Append(appKey); return sb.ToString(); } } }