How to generate a hash with a secret key

I am going to share something that we needed recently and I understand it is pretty useful in many scenarios.

Scenario:

To generate a hash using a secret key so as to add a new level of security, avoiding that someone gets into the middle and tamper the information being sent by regenerating the same hash again.

This is what is known as MAC (Message Authentication Code). In essence, the result is an encrypted hash.

Method

There are several mechanisms to generate this (HMACMD5 , HMACSHA1, etc.). Currently, Microsoft is recommending the use of SHA256, hence, I chose HMACSHA256.

Code

Here I am sharing the relevant parts of the code that allows doing this:

using System.Security.Cryptography;

        public string GetMACHash(string textToHash)

        {

            //  secret key shared by sender and receiver.

            byte[] secretkey = new Byte[64];

            string key = null;

            string result = null;

 

           //get secret key

            key = "MySecretKey"; //esto podemos invocar a un metodo que traiga este valor de la registry por ejemplo

            secretkey = System.Text.UTF8Encoding.UTF8.GetBytes(key);

 

            // Initialize the keyed hash object.

            HMACSHA256 myhmacsha256 = new HMACSHA256(secretkey);

 

            // Compute the hash of the text.

            byte[] bytedText = System.Text.UTF8Encoding.UTF8.GetBytes(textToHash);

 

            byte[] hashValue = myhmacsha256.ComputeHash(bytedText);

 

            //Base-64 Encode the results and strip off ending '==', if it exists

            result = Convert.ToBase64String(hashValue).TrimEnd("=".ToCharArray());

 

            //set response

            return result;

        }

 

References

Here is a good article that talks about MACs.

http://dotnetslackers.com/articles/security/Hashing_MACs_and_Digital_Signatures_in_NET.aspx

Here is the information about HMACSHA256 class

http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256.aspx

 

3 Comments

Comments have been disabled for this content.