说到大名鼎鼎的MD5算法,稍有经验的程序员都应该听说过,特别是做Web应用程序的开发人员。那什么是MD5呢?MD5是现在使用最广泛的一种哈希算法,它的作用就是如果哪一天你的网站被人攻破,数据被人窃取,你也不用担心用户信息泄露,因为***者看到的所有密码都只是一些没有意义的字符串而已(当然前提是你已经对密码做过加密处理)。关于于MD5的算法和能力我就不多做介绍了,网上类似的讨论已经多如牛毛,这里只是把.NET中使用MD5算法的方法做个整理。
使用System.Security.Cryptography命名空间
在.NET类库的System.Security.Cryptography下,微软给我们提供了直接使用MD5加密的方法,这也是微软C#开发组FAQ中的推荐做法,简简单单的几行代码就让我们的网站安全上升到一个新的级别。首先定义一个方法(以下代码来自C#开发组FAQ):
{
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
更简单的调用方法:
如果你不想自己定义一个新的方法,这里有另一种更简单的方式,使用HashPasswordForStoringInConfigFile() 方法,该方法位于System.Web.Security命名空间下,函数原型为:
string password,
string passwordFormat
)
调用方法:
给MD5加点“盐”
虽然MD5加密很厉害,将信息泄露的概率降低到了非常小的程度,但我们这些做程序员的具有追求完美的天性,为了达到更高的安全级别,我们还需给MD5加点“盐”。所谓的加“盐”就是当用户注册填写密码时,让系统产生一个随机值,将这个值与用户密码连接在一起再使用MD5算法进行处理,这样就在很大程度上避免了***者通过字符对比得到特定密码的危险。下面是一段从网上搜集到的实现代码:
{
public static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
public static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "sha1");
return hashedPwd;
}
public static bool PasswordMatch(string current,string salt,string savedPasswordHash)
{
string currentPasswordHash=CreatePasswordHash(current, salt);
return (currentPasswordHash == savedPasswordHash);
}
}