在很多地方请求参数需要做处理例如:
步骤
1.参数字典排序。
2.拼接字符。
/// <summary> /// 生成签名 /// </summary> /// <param name="paramlst">参数列表</param> /// <param name="IsToUpper">是否转大写</param> /// <param name="IsDirect">是否直接加上签名Key</param> /// <returns></returns> public static string GenerateSign(List<KeyValuePair<string, string>> lst,string privateKey) { Comparison<KeyValuePair<string, string>> Comparer = new Comparison<KeyValuePair<string, string>>(CompareKeyValuepair); lst.Sort(Comparer); var paramlst = lst.Where(p => !string.IsNullOrEmpty(p.Value)).ToList(); string signstr = string.Join("&", paramlst.Select(p => p.Key + "=" + p.Value)) + privateKey; return Sign(signstr, "UTF-8"); }
/// <summary> /// 根据Key比较排序位置 /// </summary> private static int CompareKeyValuepair(KeyValuePair<string, string> p1, KeyValuePair<string, string> p2) { return string.Compare(p1.Key, p2.Key); }
3.MD5加密
/// <summary> /// 签名字符串 /// </summary> /// <param name="prestr">需要签名的字符串</param> /// <param name="key">密钥</param> /// <param name="inputCharset">编码格式</param> /// <returns>签名结果</returns> public static string Sign(string prestr, string inputCharset) { StringBuilder sb = new StringBuilder(); MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(Encoding.GetEncoding(inputCharset).GetBytes(prestr)); foreach (byte t1 in t) { sb.Append(t1.ToString("x2")); } return sb.ToString(); }
第二套加密、排序方法
public static bool IdentifySign<T>(T entity, string keys = "aiHpJWIlmXhb7JrwOCon", string charSet = "utf-8") where T : new() { if (entity == null) { entity = new T(); } StringBuilder sb = new StringBuilder(); Type type = typeof(T); PropertyInfo[] pi = type.GetProperties(); var tt = pi.OrderBy(t => t.Name); string sign = ""; foreach (var item in tt) { //参数为空不参与MD5计算 if (item.GetValue(entity, null) == null) continue; if (item.Name == "sign") { sign = item.GetValue(entity, null).ToString(); continue; } if (item.GetValue(entity, null) is ICollection) { sb.Append(item.Name + "=" + Newtonsoft.Json.JsonConvert.SerializeObject(item.GetValue(entity, null)) + "&"); continue; } sb.Append(item.Name + "=" + item.GetValue(entity, null) + "&"); } string signStr = sb.ToString().TrimEnd('&') + "&key=" + keys; var urlmd5 = DESEncrypt.MD5ToUpper(signStr, charSet); return urlmd5 == sign; }
public static string LuckDrawPostSign<T>(T entity, string keys = "aiHpJWIlmXhb7JrwOCon", string charSet = "gb2312") where T : new() { if (entity == null) { entity = new T(); } StringBuilder sb = new StringBuilder(); Type type = typeof(T); PropertyInfo[] pi = type.GetProperties(); var tt = pi.OrderBy(t => t.Name); var jo = new JObject(); foreach (var item in tt) { //参数为空不参与MD5计算 if (item.GetValue(entity, null) == null) continue; sb.Append(item.Name + "=" + item.GetValue(entity, null) + "&"); jo.Add(item.Name, item.GetValue(entity, null).ToString()); } var urlmd5 = DESEncrypt.MD5ToUpper(sb.ToString() + "key=" + keys, charSet); jo.Add("sign", urlmd5); return jo.ToString(); }