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, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access