C# MD5驗證,
孫廣東 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); // 返回
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。