.NET生成常用16、32位MD5加密的两种方法

//MD5加密函数比较复杂,在.NET中我们不需要编写底层的算法。
//平台已经提供两个生成MD5加密的方法:
//经过改动一点就可以生成如现在DVBBS等论坛中使用的MD5密码

//⑴:使用C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Security.dll
public static string MD5(string Password,int Length)
{

if (Length!=16&&Length!=32) throw new System.ArgumentException("Length参数无效,只能为16位或32位");
System.Security.Cryptography.MD5CryptoServiceProvider MD5=new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] b= MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Password));
System.Text.StringBuilder StrB=new System.Text.StringBuilder();
for(int i=0;i<b.Length;i++)
StrB.Append(b[i].ToString("x").PadLeft(2,'0'));

if (Length==16)
       return StrB.ToString(8,16);
else
       return     StrB.ToString();

}


//⑵:在ASP。NET中可以直接使用System.Web.Security名称空间的FormsAuthentication类

public string md5(string str,int code)
{
if(code==16) //16位MD5加密(取32位加密的9~25字符)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ;
}  
else//32位加密
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower();
}  
}

posted @ 2009-07-21 10:14  Hayden Han  阅读(757)  评论(0编辑  收藏  举报