Checking Whether a Hash Value Matches Some Text

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

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 static CompareHash method of the Cryptographer 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.

QuickStart

For an extended example of how to use the CompareHash method to expire a token corresponding to a user identity, see Walkthrough: Checking Whether a Hash Value Matches Some Text.

Using CompareHash

The following code shows how to use the CompareHash method on data in the form of a string.

// generatedHash contains a hash value for a previously hashed string.
byte[] stringToCompare = (new UnicodeEncoding()).GetBytes("TestValue");
bool comparisonSucceeded = Cryptographer.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 = Cryptographer.CompareHash("hashProvider", stringToCompare, generatedHash)

Usage Notes

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