非空请求参数按照参数名ASCII码升序排列
最近又对接一个供应商,还在使用“非空请求参数按照参数名ASCII码升序排列”这种很老的稍不合理的方式做key/value组合字符串做验证。
还记得很多年前有很多知名的大厂也用过这种方式,但是这种真的太low了。以前还不流行json传输的时候,大家都用这种key/value组合用key排序无可厚非。
现在api都使用json方式传输了,还用这个key排序方式,简直一点用处都没有。
话不多说,下面上C#代码:
public static string Func_ASCIISort ( Dictionary<string, string> dic_NameAndValue ) #region { List<string> li_Temp; string[] tempArr; List<string> li_ResultList; li_Temp = new List<string>(); foreach (var item in dic_NameAndValue) { string key = item.Key; li_Temp.Add(key); } tempArr = li_Temp.ToArray(); Array.Sort(tempArr, StringComparer.Ordinal);//ASCII排序 li_ResultList = new List<string>(); for (int i = 0; i < tempArr.Length; i++) { string key = tempArr[i]; string value = dic_NameAndValue[key]; if (string.IsNullOrWhiteSpace(value) == false) { li_ResultList.Add(key + "=" + value); } } string string1 = string.Join("&", li_ResultList); return string1; } #endregion
直接使用 SortedDictionary
public static SortedDictionary<string, string> ProperiesDic<T>(T ent) where T : class, new() { var sortedDic = new SortedDictionary<string, string>(); var properies = typeof(T) .GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); foreach (var p in properies) { var val = p.GetValue(ent); if (val != null && !string.IsNullOrWhiteSpace(val.ToString())) { sortedDic.Add(p.Name, val.ToString()); } } return sortedDic; }
排序后直接返回MD5
 
public static string ProperiesSortDicMD5<T>(T ent) where T : class, new() { var sortedDic = new SortedDictionary<string, string>(); var properies = typeof(T) .GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); foreach (var p in properies) { var val = p.GetValue(ent); if (val != null && !string.IsNullOrWhiteSpace(val.ToString())) { sortedDic.Add(p.Name, val.ToString()); } } var sb = new System.Text.StringBuilder(); foreach (var kv in sortedDic) { sb.AppendFormat("{0}={1}&", kv.Key, kv.Value); } var sign = sb.ToString().TrimEnd('&') + "secretKey"; var md5 = CryptographyHelper.ToMD5(sign, MD5Len.To32Bit).ToUpper(); return md5; }
这种规则组合验签方式已经不常见了,其实很简单如果不知道用什么方式验签或加密,请直接参考大厂的就对了,比如Jack马啊,某微啊,很详细。也能统一标准。
 
                     
                    
                 
                    
                 
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号