數據加密總結進階(4)

 在這篇中我們將學習如何在傳輸過程中不竄改數據而達到安全目的.我們用的技術是哈希算法.哈希值會驗證數據的完整性.接收到的數據的哈希值可以和被傳出去的數據的哈希值進行比較,看它是否被竄改!

Net框架中提供了下面這幾個主要的運用哈希的類:

  • SHA1Managed
  • MD5CryptoServiceProvider
  • MACTripleDES

因爲SHA1現在已經被破譯,所以我們將使用MD5CryptoServiceProvider 類生成哈希值.

 

我們將創建一個Helper類來幫助我們用MD5算法創建和驗證哈希值.這個類包含兩個方法:GetHash()和VerifyHash();GetHash()方法接收一個要被生成哈希值的字符串,並以字節數組類型返回這個竄的哈希值.VerifyHash()方法接收GetHash()方法返回的哈希值和要進行比較的字符串,如果在傳輸過程中沒有被竄改這個方法將返加True,否則返回False;



Let's dissect the code step by step:讓我們一步步解釋:

  • We first need to import System.Security.Cryptography namespace in your class

        導入命名空間:System.Security.Cryptography

  • The GetHash() accepts string whose hash value is to be generated and returns the computed hash as a byte array.

        GetHash()方法接收一個要被生成哈希值的字符串,並以字節數組類型返回這個竄的哈希值.

  • Inside the function we used UTF8Encoding class and get aa byte representation of the string to be transfered.

        在方法內部我們用UTF8Encoding類得到要被傳輸字符串的字節類型.

  • We then create an instance of MD5CryptoServiceProvider class and call its ComputeHash by passing the byte created above to it.

        然後,我們創建MD5CryptoServiceProvider類的實例,並且通過傳遞上一步創建的字節調用這個實例的ComputeHash()方法.

  • The ComputeHash() function generates the hash for the given data and returns another byte array that represents the hash value of the data.

        ComputeHash()方法生成數據的哈希值,並返回這個數據的哈希值的數組.

  • The VerifyHash() function accepts the message as it was received and the hash generated previously and returns true if the message is not altered during transmit otherwise returns false.

       VerifyHash()方法接收GetHash()方法返回的哈希值和要進行比較的字符串,如果在傳輸過程中沒有被竄改這個方法將返加True,否則返回False;

  • Inside this function we again use UTF8Encoding class and generate byte representation of the received message.

       在這個方法內我們再次用到了UTF8Encoding 類生成接收數據的字數組.

  • We then compute hash for this data using the same ComputeHash() method of MD5CryptoServiceProvider class.

       然後我們用MD5CryptoServiceProvider類的 ComputeHash() 方法來運算哈希值.

  • Finally, we run a for loop and check each and every byte of original hash value and the hash we generated above. If both the hash values are matching we can conclude that the data is not tampered.

        最後,我們用一個循環檢查原字符串的哈希值和我們生成的有什麼不同.如果哈希值匹配我們就能斷定數據沒被竄改過.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章