Jaa


Checking Whether a Hash Value Matches Some Text

An example of when you would check whether a hash matches some text is when you have to verify that data has not been changed in transit over a network. In this case, the hash value for the data would be stored at the server, and when the data arrives at the server, it is compared against the hash value.

Typical Goals

In this scenario, the goal is to compare plaintext with data that has a pre-generated hash value for the data; by doing this, you can verify that data has not been changed.

Solution

Make sure that the data types match, either by converting the plaintext to a byte array or by converting the hashed data to a string. Call the appropriate overload of the CompareHash method of the CryptographyManager class to obtain the hash, specifying the data to hash as a string or a byte array, a pre-generated hash to compare it with as a string or a byte array, and the name of the configured hash provider to be used.

Using CompareHash

The following code shows how to use the CompareHash method on data in the form of a string. These examples assume you have obtained an instance of the CryptographyManager class through the Enterprise Library container and saved it in the variable named crypto.

// generatedHash contains a hash value for a previously hashed string.
byte[] stringToCompare = (new UnicodeEncoding()).GetBytes("TestValue");
bool comparisonSucceeded = crypto.CompareHash("hashProvider", stringToCompare, generatedHash);
'Usage
' generatedHash contains a hash value for a previously hashed string. 
Dim stringToCompare = (New UnicodeEncoding()).GetBytes("TestValue")
Dim comparisonSucceeded As Boolean = crypto.CompareHash("hashProvider", stringToCompare, generatedHash)

Usage Notes

Make sure you specify a hash provider in the Enterprise Library configuration tools.