13.4 Programming Keyed Hashing Algorithms

The .NET Framework has a much more direct model for representing
keyed hashing algorithms. There are no abstract classes for different
algorithms, meaning that there can be only one implementation of each
keyed algorithm. Figure 13-7 shows the class
hierarchy for keyed hashing algorithms.

13.4.1 The KeyedHashAlgorithm Class

The KeyedHashAlgorithm class extends
HashAlgorithm, adding a new property called
Key, which is used to get and set the secret key
as a byte array. Aside from this addition, the
KeyedHashAlgorithm class provides the same
abstraction benefits as using HashAlgorithm for
creating normal hash codes.

13.4.2 Instantiating the Algorithm

The process of
creating instances of keyed algorithms is much the same as for normal
hashing algorithms. You can create algorithms directly using the
implementation class name, or indirectly using the
Create method of the
KeyedHashingAlgorithm class.

When using the direct approach, you can supply the secret key as an
argument to the class constructor. In the following fragment, use the
System.Text.Encoding class to convert a
string into a byte array and to
initialize the keyed hashing algorithm:

These statements create an instance of the HMAC-SHA-1 implementation
class, using the key "This is my secret
key." When using the Create
method, the key value is set separately, using the
Key property. The following fragment demonstrates
how to do this:

The Create method creates an algorithm class based
on the value of the string argument. Table 13-4
lists the mapping between string values and implementation classes
for keyed hashing algorithms.

If you do not supply a string as an argument to the
Create method, the
System.Security.Cryptography.HMACSHA1 algorithm will be used as a default.
If you use a string that is not one of the values listed in Table 13-4, then a
System.NullReferenceException will be thrown.

Table 13-4. Mapping string values to keyed algorithm classes

String value

Algorithm implementation class

HMACSHA1

HMACSHA1

System.Security.Cryptography.HMACSHA1

HMACSHA1

MACTripleDES

MACTripleDES

System.Security.Cryptography.MACTripleDES

MACTripleDES

13.4.3 Hashing Data and Validating Hash Codes

Because the KeyedHashAlgorithm class derives from
HashAlgorithm, the processes for creating and
validating keyed hash codes is the same as for normal hash codes,
with the exception that the value of the key should be set either as
a constructor argument or as using the Key
property. For reference, Example 13-2 demonstrates
how to create a keyed hash code from a byte array of data:

You must set the secret key value before creating the hash code;
otherwise, the KeyedHashAlgorithm will create a
random key. See Chapter 17 for more information
about creating and managing keys.