Cryptography Using .NET: Message Authentication

1. Message Authentication.  The .NET Framework supports five hashing algorithms, (MD5, SHA-1, SHA-256, SHA384, and SHA-512) and two keyed hashing algorithms (HMAC-SHA-1 and MAC-Triple-DES).

2. Hashing Algorithms.  An implementation of the hashing algorithm is much simpler than the encryption demonstrated in the previous section on Symmetric Encryption.  In this section, you will not have to use the ICryptoTransform, CryptoStream, and MemoryStream objectsThe following table lists the hashing algorithms. 

Hashing Algorithm Input block size (bits) Hash code size (bits)
MD5 512 128
SHA-1 512 160
SHA-256 512 256
SHA-384 1024 384
SHA-512 1024 512

To create an instance of the hashing implementation class HashAlgorithm, you would use HashAlgorithm h_alg = HashAlgorithm.Create("SHA256");  to create the object h_alg, for the SHA-256 algorithm. You can omit the hyphen between SHA and the number 256. For example, you can use either SHA-256 or SHA256 for an argument of the Create method.  To compute a hash code, you should use the ComputeHash method of the HashAlgorithm class as: byte[] h_code = h_alg.ComputeHash(byte[] message);  This method takes a byte array of a message as an argument, and returns a byte array of a hash code.

3. Keyed Hashing Algorithms.  The hashing algorithms can be made even more secure by using a secret key. The .NET Framework supports two hybrid types of keyed hashing algorithm as follows.

  • The HMAC-SHA-1 algorithm is a combination of the HMAC and SHA-1 algorithm. The MAC-Triple-DES algorithm uses the Triple-DES to create a block hash code.
  • The KeyedHashAlgorithm class defines these two algorithms. Thus, an object of the keyed hashing algorithm, h_alg, can be created as KeyedHashAlgorithm h_alg = KeyedHashAlgorithm.Create("HMACSHA1");

The Create method will take a string value, HMACSHA1 for the HMAC-SHA-1 algorithm, and MACTripleDES for the MAC-Triple-DES algorithm.  Since you are dealing with keyed hashing algorithms here, how would you set up the key?  You can use the same concept as described in the symmetric encryption section to set up the key.  Again, both the message and key must be converted to byte arrays before hashing. After setting the key value, you can compute a hash code using the ComputeHash method, similar to what described in the Hashing Algorithms section.