C# MD5驗證,

來源:互聯網
上載者:User

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);  // 返回






著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.