标准MD5 .Net,实现!的对与错!
关键之处在,从byte到字符串的处理
下面是一个错误的实现!
/// <summary>
/// 返回32位md5十六进制加密
/// </summary>
/// <param name="strValue">待加密的字符串</param>
/// <returns></returns>
public string GetHexMd5String(string strValue)
{
string strReturn = "";
byte[] data = Encoding.Unicode.GetBytes(strValue);
MD5 md5 = MD5CryptoServiceProvider.Create();
md5.ComputeHash(data);
//下面从byte到字符串转换有问题!
for (int i=0; i<md5.Hash.Length; i++)
{
string strHex = md5.Hash[i].ToString("X2").ToLower();
//if(strHex.Length==1)
// strHex = "0"+strHex;
strReturn += strHex;
}
return strReturn;
}
/// 返回32位md5十六进制加密
/// </summary>
/// <param name="strValue">待加密的字符串</param>
/// <returns></returns>
public string GetHexMd5String(string strValue)
{
string strReturn = "";
byte[] data = Encoding.Unicode.GetBytes(strValue);
MD5 md5 = MD5CryptoServiceProvider.Create();
md5.ComputeHash(data);
//下面从byte到字符串转换有问题!
for (int i=0; i<md5.Hash.Length; i++)
{
string strHex = md5.Hash[i].ToString("X2").ToLower();
//if(strHex.Length==1)
// strHex = "0"+strHex;
strReturn += strHex;
}
return strReturn;
}
结算加密出来的结果,写java,php,asp等标准算法不同!
其实在.net 有一个最简单实现MD5的方法
/// <summary>
/// MD5加密
/// </summary>
/// <param name="toCryString">被加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string toCryString)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(toCryString, "MD5");
}
/// MD5加密
/// </summary>
/// <param name="toCryString">被加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string toCryString)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(toCryString, "MD5");
}
那么,从byte到字符串的标准转法怎么转呢,我看了,Quickstart用的是
BitConverter.ToString
这样标准md5写法要写成!
public static string MD5(string toCryString)
{
MD5CryptoServiceProvider hashmd5;
hashmd5 = new MD5CryptoServiceProvider();
return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(toCryString))).Replace("-","").ToLower();//asp是小写,把所有字符变小写
}
{
MD5CryptoServiceProvider hashmd5;
hashmd5 = new MD5CryptoServiceProvider();
return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(toCryString))).Replace("-","").ToLower();//asp是小写,把所有字符变小写
}
结果加密出来的内容,和标准的一样了!