Check 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, allowing you to verify that data has not been changed.

Solution

Make sure that the data types match, either by converting the plain text to a byte array or by converting the hashed data to a string. Call the appropriate overload (string or byte array) of the static method CompareHash on the Cryptographer class to obtain the hash, specifying the data to hash, and a pre-generated hash to compare it with, along with 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: Check Whether a Hash 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 Notes

Make sure you specify a hash provider in the Enterprise Library Configuration Console.

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.
Show: