在 asp 时代,对字符串进行 MD5 方法,均使用网上流行的 MD5 加密函数。
用 .net 编写程序时,则可以使用 .Net 自带的 MD5 类,MD5 类在于 System.Security.Cryptography 命名空间里,该命名空间提供加密服务,包括安全的数据编码和解码,以及许多其他操作,例如散列法、随机数字生成和消息身份验证。其中包括 HashAlgorithm、MD5、MD5CryptoServiceProvider 等类。
MD5 类继承于加密哈希算法基类(HashAlgorithm),表示 MD5 哈希算法的所有实现均从中继承的抽象类。
一般地,使用 MD5 加密服务提供程序类(MD5CryptoServiceProvider)来对字符串进行 MD5 加密:
public static string Md5(string strPassword, int code)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
if (code == 16)
return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(strPassword))).Replace("-", "").ToLower().Substring(8, 16);
else
return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(strPassword))).Replace("-", "").ToLower();
}
如果是用于 Web 的,还可以用 System.Web.Security.FormsAuthentication 类的 HashPasswordForStoringInConfigFile 方法:
public static string Md5(string strPassword, int code)
{
if (code == 16)
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strPassword,"MD5").ToLower().Substring(8, 16);
else
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strPassword,"MD5").ToLower();
}