当前位置:首页 > ASP.NET实例:MD5简单加密

ASP.NET实例:MD5简单加密

点击次数:878  更新日期:2010-12-28
\n


\n

其实在.net 有一个最简单实现MD5的方法


\n

<summary>
/**//// MD5加密
///
</summary>
/// <param name=”toCryString”>被加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string toCryString)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(toCryString, “MD5″);
}


\n

方法2:


\n

using System.Security.Cryptography;


\n

public static string MD5(string str)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(str));
string str2 = “”;
for(int i=0;i<result.Length;i++)
{
str2 += string.Format(“{0:x}”,result[i]);
}
return str2;
}


\n

方法3:


\n

asp.net自带了一个MD5和SHA1加密类库!
下面是调用此类库的两种加密方法:


\n

=====================


\n

public string GetMD5(string strData)
{
//使用MD5加密方法:
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] md5Bytes = System.Text.Encoding.Default.GetBytes(strData);
byte[] cryString = md5.ComputeHash(md5Bytes);
string md5Str = string.Empty;
for (int i=0;i<cryString.Length;i++)
{
md5Str += cryString[i].ToString(“X2″);
}
return md5Str;
}


\n

public string GetEncrypt(string strData,string strType)
{
//使用MD5或SHA1的加密方法:
string strCryData = string.Empty;
if (strType.ToUpper() == “SHA1″)
{
strCryData = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strData,”SHA1″);
}
else if (strType.ToUpper() == “MD5″)
{
strCryData = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strData,”MD5″);
}
return strCryData;
}

来源:csdn

\n