孫廣東 2014.6.24
數據經網絡傳輸後會變得非常不安全,最簡單有效的解決方案是給數據加一個密鑰,使用MD5 算法算出校驗碼,服務器收到數據和校驗碼後在進行比較校驗碼是否正確,以此來判斷數據是否修改過。 PHP生成 的 MD5 校驗默認為32位的字符串, 而C#默認的是16位的字節數組,需要略加修改,轉為32個字節的字符串,代碼如下:
public static string Md5Sum(string strToEncrypt)
{
// 將需要加密的字符串轉為byte數組
byte[] bs = UTF8Encoding.UTF8.GetBytes(strToEncrypt);
// 創建md5 對象
System.Security.Cryptography.MD5 md5;
md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
// 生成16位的二進制校驗碼
byte[] hashBytes = md5.ComputeHash(bs);
// 轉為32位字符串
string hashString = ;
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
使用這個 MD5 函數非常簡單, 在下面的代碼示例中,數據是包含有 “hello world” 的一個字符串, 密鑰位123, 使用Md5Sum算出32位的校驗碼字符串。
string data = hello world;
string key = 123;
Md5Sum(data + key); // 返回
