Jaa


Obtaining a Hash Value

An example of when you might want to obtain a hash value is when you have a password that you do not want to pass over the network.

Typical Goals

In this scenario, the goal is to use the block to generate a hash value from input data.

Solution

Call the appropriate overload of the CreateHash method of the CryptographyManager class to obtain the hash, specifying the data to be hashed as a string or a byte array and supplying the name of the configured hash provider.

Using CreateHash

The following code shows how to use the CreateHash 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.

byte[] valueToHash = (new UnicodeEncoding()).GetBytes("password");
byte[] generatedHash = crypto.CreateHash("hashProvider", valueToHash);

// Clear the byte array memory.
Array.Clear(valueToHash, 0, valueToHash.Length);
'Usage
Dim valueToHash = (New UnicodeEncoding).GetBytes("password")
Dim generatedHash As Byte() = crypto.CreateHash("hashProvider", valueToHash)

' Clear the byte array memory.
Array.Clear(valueToHash, 0, valueToHash.Length)

Usage Notes

Consider the following points when you create a hash value:

  • The CreateHash method takes two overloads. The overload you use depends on whether you are creating a hash from a string or byte array.
  • Make sure that you specify a hash provider in the Enterprise Library configuration tools.
  • Sensitive data should be cleared in memory as soon as possible. Leaving sensitive data unencrypted in memory can expose the data to security risks. You should note that data in memory may also end up on the hard disk, because the operating system can write data to a swap file. Also, if the computer crashes, the operating system can dump the contents of memory to disk.