說到大名鼎鼎的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);
}
}