Thursday, October 15, 2015

Cryptographic Hash-based Message Authentication Code (HMAC) Algorithm in .NET C#

If we combine one way hash functions with secret cryptographic key that's called HMAC. like hash code the HMAC is used to verify the integrity of the code. It is also allow us to verify the authentication of the message. Only the person who has the key can calculate the hash. This HMAC can be used with different hashing methods like MD5 and SHA family.

So the HMAC is used to check both the integrity and authenticity. For example, assume that you are sending a message and hash. Receiver can verify it by comparing with hash he received. However we are not sure weather the message will be delivered to the person to whom you need to send. So using a private key we can secure the message. Using the same key he can recompute the HMAC and compare it with the HMAC you sent. That ensures the authenticity.

The code implementation is same as what we did in MD5 and SHA family samples in my previous post except only one change that we have to pass a private key to the hashing method. The primary key can be generated using another cryptocraphic method called RNGCryptoServiceProvider. That I have explained in my another post Generate Random numbers using RNGCryptoServiceProvider in C#.

HMAC SHA-512 Sample
using System;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    var key = GenerateKey();

    const string message1 = "The quick brown fox jumps over the lazy dog";
    const string message2 = "The quick brown fox jumps over the lazy dog.";

    Console.WriteLine("Original Message 1 : " + message1);
    Console.WriteLine("Original Message 2 : " + message2);
    Console.WriteLine();

    var hmacMessage = ComputeHmacHash(Encoding.UTF8.GetBytes(message1), key);
    var hmacMessage2 = ComputeHmacHash(Encoding.UTF8.GetBytes(message2), key);

    Console.WriteLine();
    Console.WriteLine("HMAC SHA-512 Hash");
    Console.WriteLine();
    Console.WriteLine("Message 1 hash = " + Convert.ToBase64String(hmacMessage));
    Console.WriteLine("Message 2 hash = " + Convert.ToBase64String(hmacMessage2));
    Console.ReadLine();
}
public static byte[] ComputeHmacHash(byte[] toBeHashed, byte[] key)
{
    using (var hmac = new HMACSHA512(key))
    {
        return hmac.ComputeHash(toBeHashed);
    }
}
public static byte[] GenerateKey()
{
    const int KeySize = 32;

    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[KeySize];
        randomNumberGenerator.GetBytes(randomNumber);

        return randomNumber;
    }
}
Output 

The same way we can implement the HMAC for HMAC MD5, HMAC SHA1, HMAC SHA-256 and HMAC SHA-512 using its corresponding class HMACMD5(key),  HMACSHA1(key) and HMACSHA256(key).

No comments:

Post a Comment