MD5加密算法

MD5加密整理
2008-01-20 09:29:30
 标签:.net MD5   [推送到博客圈]

说到大名鼎鼎的MD5算法,稍有经验的程序员都应该听说过,特别是做Web应用程序的开发人员。那什么是MD5呢?MD5是现在使用最广泛的一种哈希算法,它的作用就是如果哪一天你的网站被人攻破,数据被人窃取,你也不用担心用户信息泄露,因为攻击者看到的所有密码都只是一些没有意义的字符串而已(当然前提是你已经对密码做过加密处理)。关于于MD5的算法和能力我就不多做介绍了,网上类似的讨论已经多如牛毛,这里只是把.NET中使用MD5算法的方法做个整理。

使用System.Security.Cryptography命名空间
   在.NET类库的System.Security.Cryptography下,微软给我们提供了直接使用MD5加密的方法,这也是微软C#开发组FAQ中的推荐做法,简简单单的几行代码就让我们的网站安全上升到一个新的级别。首先定义一个方法(以下代码来自C#开发组FAQ):
   
public string CalculateMD5Hash(string input)
{
    // 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();
}
   调用方法:
string hash = CalculateMD5Hash("abcdefghijklmnopqrstuvwxyz");
   返回值为一个32位的字符串:C3FCD3D76192E4007DFB496CCA67E13B

更简单的调用方法:
   
如果你不想自己定义一个新的方法,这里有另一种更简单的方式,使用HashPasswordForStoringInConfigFile() 方法,该方法位于System.Web.Security命名空间下,函数原型为:
public static string HashPasswordForStoringInConfigFile (
    string password,
    string passwordFormat
)
    其中password就是你要加密的密码,passwordFormat表示加密方式,只能取FormsAuthPasswordFormat类型的值,否则会发生异常,这里有三种选择:"Clear"、"SHA1"、"MD5",分别表示明文显示、使用SHA1算法、使用MD5算法。
    调用方法: 
string hash = HashPasswordForStoringInConfigFile("abcdefghijklmnopqrstuvwxyz");
    返回值与上面一样。

给MD5加点“盐”
   
虽然MD5加密很厉害,将信息泄露的概率降低到了非常小的程度,但我们这些做程序员的具有追求完美的天性,为了达到更高的安全级别,我们还需给MD5加点“盐”。所谓的加“盐”就是当用户注册填写密码时,让系统产生一个随机值,将这个值与用户密码连接在一起再使用MD5算法进行处理,这样就在很大程度上避免了攻击者通过字符对比得到特定密码的危险。下面是一段从网上搜集到的实现代码:
public class PasswordHelper
    {
        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);
        }
    }
这里和大家分享和学习如何学IT!
原文地址:https://www.cnblogs.com/fuchifeng/p/1129242.html