工具类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication1
{
public class MD5Help
{
/// <summary>
/// 签名字符串
/// </summary>
/// <param name="prestr">需要签名的字符串</param>
/// <param name="key">密钥</param>
/// <param name="_input_charset">编码格式</param>
/// <returns>签名结果</returns>
public static string Sign(string prestr,string key, string _input_charset = "UTF-8")
{
StringBuilder sb = new StringBuilder(32);
if (!string.IsNullOrEmpty(key))
{
prestr += "&key="+key;
}
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
for (int i = 0; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
}
return sb.ToString();
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="prestr">需要签名的字符串</param>
/// <param name="sign">签名结果</param>
/// <param name="key">密钥</param>
/// <param name="_input_charset">编码格式</param>
/// <returns>验证结果</returns>
public static bool Verify(string prestr, string sign, string key, string _input_charset = "UTF-8")
{
string mysign = Sign(prestr, key);
if (mysign == sign)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 字典排序
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static string DictonarySort(Dictionary<string, string> dic)
{
string buff = "";
var dicSort = from objDic in dic orderby objDic.Key select objDic;
foreach (KeyValuePair<string, string> kvp in dicSort)
{
if (kvp.Key != "sign" && kvp.Value.ToString() != "")
{
buff += kvp.Key + "=" + kvp.Value + "&";
}
}
buff = buff.Trim('&');
return buff;
}
}
}
MD5加密和验签调用:
string Key = "n7SHGuJyxaXx5P5vfTDTtesNrfBXyDcU";
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("card_name", "oQIU0oNpEPzyxx8q81LQgQ==");
dic.Add("card_no", "padyOLDkFQE2OY1pSYbilXW6DMybMJvxTqNkP5WlRJg=");
dic.Add("card_type", "2");
dic.Add("encrypt_method", "1");
dic.Add("id_no", "Vs6/CIRNeWZ1RE3G/L6IajLF8Pt2XRR0nBBau1W/cpE=");
dic.Add("id_type", "1");
dic.Add("input_charset", "1");
dic.Add("need_send_sms", "1");
dic.Add("phone", "5ULTz/mMrbfEFMJZvoNkpA==");
dic.Add("service_code", "2");
dic.Add("sp_no", "1000132454");
dic.Add("version", "1");
dic.Add("sign_method", "1");
string str = MD5Help.DictonarySort(dic);
Console.WriteLine("排序:" + str);
string s = MD5Help.Sign(str, Key);
Console.WriteLine("Sign:" + s);
bool bl = MD5Help.Verify(str, s, Key);
Console.WriteLine("验签:" + bl);