//根据属性列表计算签名 private string CalculateSign(SortedList <string, string> properties, WechatPaySignType signType) { StringBuilder stringA = new StringBuilder(); bool isFirst = true; foreach (KeyValuePair <string, string> item in properties) { if (item.Key == "sign") { continue; } if (isFirst == false) { stringA.Append("&"); } else { isFirst = false; } stringA.Append(item.Key); stringA.Append("="); stringA.Append(item.Value); } stringA.Append("&key="); stringA.Append(this._settings.SecurityKey); byte[] hash = null; if (signType == WechatPaySignType.MD5) { MD5 md5 = MD5.Create(); md5.Initialize(); hash = md5.ComputeHash(Encoding.UTF8.GetBytes(stringA.ToString())); } else { Console.WriteLine(stringA.ToString()); KeyedHashAlgorithm hashAlgo = new HMACSHA256( Encoding.UTF8.GetBytes(this._settings.SecurityKey) ); hashAlgo.Initialize(); hash = hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(stringA.ToString())); } if (hash == null) { throw new InvalidOperationException(nameof(hash)); } StringBuilder signBuilder = new StringBuilder(); for (int i = 0; i < 32; i++) { signBuilder.Append(hash[i].ToString("X2")); } return(signBuilder.ToString()); }
public static string SignTypeTransfer(WechatPaySignType signType) { switch (signType) { case WechatPaySignType.MD5: return("MD5"); case WechatPaySignType.HMACSHA256: return("HMAC-SHA256"); default: throw new ArgumentNullException(nameof(signType)); } }