17.5. Verifying That a String Remains Uncorrupted Following Transmission
Problem
You have some text that will be sent across a network to another machine for processing. You need to verify that this message has not been modified in transit.
Solution
Calculate a hash value from the string and append it to the string before it is sent to its destination. Once the destination receives the string, it can remove the hash value and determine whether the string is the same one that was initially sent. It is critical that both sides agree on a hash algorithm that will be used. The SHA-256 algorithm is a good choice and an industry standard.
The CreateStringHash
method takes a string
as input, adds a hash value to the end of it, and returns the new string
, as shown in Recipe 17.5.
Example 17-8. Verifying that a string remains uncorrupted following transmission
public class HashOps { // The number 44 is the exact length of the base64 representation // of the hash value, which was appended to the string. private const int HASH_LENGTH = 44; public static string CreateStringHash(string unHashedString) { byte[] encodedUnHashedString = Encoding.Unicode.GetBytes(unHashedString); string stringWithHash = ""; using (SHA256Managed hashingObj = new SHA256Managed( )) { byte[] hashCode = hashingObj.ComputeHash(encodedUnHashedString); string hashBase64 = Convert.ToBase64String(hashCode); stringWithHash = unHashedString + hashBase64; } return (stringWithHash); } public static bool IsStringCorrupted(string stringWithHash, ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.