O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.5. Verifying that a String Is Uncorrupted During Transmission

Problem

You have some text that will be sent across a network to another machine for processing. It is critical that you are able to verify that this text remains intact and unmodified when it arrives at its destination.

Solution

Calculate a hash value from this 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. The CreateStringHash method takes a string as input, adds a hash value to the end of it, and returns the new string:

public class HashOps { public static string CreateStringHash(string unHashedString) { byte[] encodedUnHashedString = Encoding.Unicode.GetBytes(unHashedString); SHA256Managed hashingObj = new SHA256Managed( ); byte[] hashCode = hashingObj.ComputeHash(encodedUnHashedString); string hashBase64 = Convert.ToBase64String(hashCode); string stringWithHash = unHashedString + hashBase64; hashingObj.Clear( ); return (stringWithHash); } public static bool TestReceivedStringHash(string stringWithHash, out string originalStr) { // Code to quickly test the handling of a tampered string //stringWithHash = stringWithHash.Replace('a', 'b'); if (stringWithHash.Length < 45) { originalStr = null; return (true); } string hashCodeString = stringWithHash.Substring(stringWithHash.Length - 44); string unHashedString = stringWithHash.Substring(0, stringWithHash.Length ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required