今天在開發一個軟件時,同時在B/S版和C/S版中都要用到MD5加密,在
ASP.NET中使用的是 ide
/**//// <summary>
/// 取得MD5加密串
/// </summary>
/// <param name="input">源明文字符串</param>
/// <returns>密文字符串</returns>
public static string GetMD5Hash(string input)
...{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strOriginal, "MD5");
}
的加密方式;
而在WinForm中用的是 ui
/**//// <summary>
/// 取得MD5加密串
/// </summary>
/// <param name="input">源明文字符串</param>
/// <returns>密文字符串</returns>
public static string GetMD5Hash(string input)
...{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.Default.GetBytes(input);
bs = md5.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
...{
s.Append(b.ToString("x2").ToUpper());
}
string password = s.ToString();
return password;
}
但發現一樣一個字符串,兩種方式得出的密文是不同的,最後才發現原來是編碼方式致使的,ASP.NET裏默認的是UTF-8編碼,把WinForm程序裏的System.Text.Encoding.Default.GetBytes(input);替換成System.Text.Encoding.UTF8.GetBytes(input);便可
最終正確版: 編碼
/**//// <summary>
/// 取得MD5加密串
/// </summary>
/// <param name="input">源明文字符串</param>
/// <returns>密文字符串</returns>
public static string GetMD5Hash(string input)
...{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = md5.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
...{
s.Append(b.ToString("x2").ToUpper());
}
string password = s.ToString();
return password;
}加密