Obtaining and Comparing Hash Values
To create and compare hash values, you use a hash provider. As you saw earlier, the Cryptography block includes several hash providers. The examples we provide use two of these: the SHA512 hash algorithm provider and the MD5Cng hash algorithm provider. The examples demonstrate how to use these providers to create a hash for both a text string and an object (in our example this is a simple class named Product), and how to compare the generated hashes with the original and other text strings and object instances.
The Cryptography Manager exposes two methods for working with hash providers:
The CreateHash method takes as parameters the name of a hash provider configured in the Cryptography block for the application, and the item for which it will create the hash value. There are two overloads of this method. One accepts a string and returns the hash as a string. The second overload accepts the data to encrypt as a byte array, and returns a byte array containing the hash value.
The CompareHash method takes as parameters the name of a hash provider configured in the Cryptography block for the application, the un-hashed item to compare the hash with, and the hash value to compare to the un-hashed item. There are two overloads of this method. One accepts the un-hashed item and the hash as strings. The second overload accepts the un-hashed item and the hash as byte arrays.
Creating and Comparing Hash Values for Text Strings
The example Create and Compare Hash Values for Text Strings uses the SHA512 hash algorithm provider to create a hash of three text strings. It then compares these hashes with the original and other values to demonstrate how even a minor difference between the original strings creates different hash values.
The code shown below creates three text strings that will be hashed. Notice that the second and third vary only in the letter case of two words. Then the code uses the CreateHash method of the Cryptography Manager to create the hashes of these three strings. In each case, the code passes to the CreateHash method the name of the SHA512 hash algorithm provider defined in the configuration of the application, and the text string.
Next, the code performs three comparisons of the hash values using the CompareHash method of the Cryptography Manager. It compares the hash of the first string with first string itself, to prove that they are equivalent. Then it compares the hash of the first string with the second string, to provide that they are not equivalent. Finally, it compares the hash of the second string with the third string, which varies only in letter case, to prove that these are also not equivalent.
As in earlier examples, we've removed some of the lines of code that simply write values to the console screen to make it easier to see the code that actually does the work.
// Define the text strings instance to encrypt.string sample1Text = "This is some text to hash.";string sample2Text = "This is some more text to hash.";string sample3Text = "This is Some More text to hash.";// Create the hash values using the SHA512 Hash Algorithm Provider.// The overload of the CreateHash method that takes a// string returns the result as a string.string hashed1Text = defaultCrypto.CreateHash("SHA512CryptoServiceProvider", sample1Text);string hashed2Text = defaultCrypto.CreateHash("SHA512CryptoServiceProvider", sample2Text);string hashed3Text = defaultCrypto.CreateHash("SHA512CryptoServiceProvider", sample3Text);// Compare the strings with some of the hashed values.Console.WriteLine("Comparing the string '{0}' with the hash of this string:", sample1Text);Console.WriteLine("- result is {0}", defaultCrypto.CompareHash("SHA512CryptoServiceProvider", sample1Text, hashed1Text));Console.WriteLine("Comparing the string '{0}' with hash of the string '{1}'", sample1Text, sample2Text);Console.WriteLine("- result is {0}", defaultCrypto.CompareHash("SHA512CryptoServiceProvider", sample2Text, hashed1Text));Console.WriteLine("Comparing the string '{0}' with hash of the string '{1}'", sample2Text, sample3Text);Console.WriteLine("- result is {0}", defaultCrypto.CompareHash("SHA512CryptoServiceProvider", sample3Text, hashed2Text));
If you run this example, you'll see the output shown below. You can see the hash values of the three text strings, and the result of the three hash comparisons.
Text strings to hash and the resulting hash values are:This is some text to hash.v38snPJbuCtwfMUSNRjsgDqu4PB7ok7LQ2id4RJMZUGlhn+LTgX3FNEVuUbauokCpiCzzfZI2d9sNjlo56NmuZ/8FY2sknxrD262TLSSYSQ=This is some more text to hash.braokQ/wraq9WVnKSqBROBUNG2lBwiICwX0lTGPSaooaJXL7/WcJvUCtBry8+0iRg+Rij5Xiz56jD4ZmxcKrp7kGVDeWuA7jHeYiFZmGbOU=This is Some More text to hash.aw3anokiiBXPJfxZ5kf2SrlTEN3lokVlT+46t0V1B7der1wsNTD4dPxKQly8SDAjoCgCWwzSCh4k+OUfO6/y6JIpFtWpQDqHO3JH+Rj25K0=Comparing the string 'This is some text to hash.' with the hash of this string:- result is TrueComparing the string 'This is some text to hash.' with hash of the string 'This is some more text to hash.'- result is FalseComparing the string 'This is some more text to hash.' with hash of the string'This is Some More text to hash.'- result is False
Creating and Comparing Hash Values for Object Instances
The example Create and Compare Hash Values for Data Items uses the MD5Cng hash algorithm provider to create a hash of two instances of the Product class defined within the example project, demonstrating how different property values produce a different hash value. It then compares the second object instance with the hash of the first to show that they are different.
The code shown below starts by creating an instance of the Product class, and then serializes it using the ToBytes method of the SerializationUtility class. Then it calls the CreateHash method of the Cryptography Manager, passing to it the name of the MD5Cng hash algorithm provider defined in the configuration of the application, and the byte array generated from the Product class instance.
Next, the code repeats the process with another new instance of the Product class, with different values for its properties, and displays the hash of this to show that it is different from the other instance of the Product class created previously. Finally, the code compares the hash of the first instance of the Product class with the second instance of the same class to prove that they are not equivalent.
As in earlier examples, we've removed some of the lines of code that simply write values to the console screen to make it easier to see the code that actually does the work.
// Create the object instance to encrypt.Product sample1Object = new Product(42, "Exciting Thing", "Something to keep you on your toes.");// Create the hash values using the SHA512 Hash Algorithm Provider.// Must serialize the object to a byte array first. One easy way is to use// the methods of the SerializationUtility class from the Caching block.byte[] serializedObject = SerializationUtility.ToBytes(sample1Object);// The overload of the CreateHash method that takes a// byte array returns the result as a byte array.byte[] hashed1Object = defaultCrypto.CreateHash("MD5Cng", serializedObject);// Do the same to generate a hash for another similar object with// different property values.Product sample2Object = new Product(79, "Fun Thing", "Something to keep the grandchildren quiet.");serializedObject = SerializationUtility.ToBytes(sample2Object);byte[] hashed2Object = defaultCrypto.CreateHash("MD5Cng", serializedObject);Console.WriteLine("Generated hash (when Base-64 encoded for display) is:");Console.WriteLine(Convert.ToBase64String(hashed2Object));Console.WriteLine();// Compare the hashed values.Console.WriteLine("Comparing second object with hash of the first object:");Console.WriteLine("- result is {0}", defaultCrypto.CompareHash("MD5Cng", serializedObject, hashed1Object));
If you run this example, you'll see the output shown below. You can see the hash values of the two instances of the Product class, and the result of the hash comparison.
First object to hash is 'CryptographyExample.Product' - Product.ID = 42 - Product.Name = Exciting Thing - Product.Description = Something to keep you on your toes.Generated hash (when Base-64 encoded for display) is:Gd2V77Zau/pgOcg1A2A5zk6RTd5zFFnHKXfhVx8LEi4=Second object to hash is 'CryptographyExample.Product' - Product.ID = 79 - Product.Name = Fun Thing - Product.Description = Something to keep the grandchildren quiet.Generated hash (when Base-64 encoded for display) is:1Eyal+AHf3e2QyEB+sqsGDOdux1Iom4z0zGLYlHlC78=Comparing second object with hash of the first object:- result is False