Skip Navigation Links.

ASP.NET 2.0 HMAC Example

HMAC is a message authentication code (MAC) and can be used to verify the integ-rity and authentication of a message. It involves hashing a message with a secret key. As with any MAC, it can be used with standard hash function, such as MD5 or SHA-1, which results in methods such as HMAC-MD5 or HMAC-SHA-1. As with any hashing function, the strength depends on the quality of the hashing function, and the resulting number of code bits. Along with this the number of bits in the secret key is a factor.

Message:

Key:

  

HMAC is:

Try it with a message of "testing123" and a key of "hello", and you should get:

AC2C2E614882CE7158F69B7E3B12114465945D01

The code is:

protected void Button3_Click(object sender, EventArgs e)
{
string message;
string key;

key = this.key.Text;
message = this.message.Text;

System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();

byte [] keyByte = encoding.GetBytes(key);

HMACSHA1 hmac = new HMACSHA1(keyByte);

byte [] messageBytes = encoding.GetBytes(message);

byte [] hashmessage = hmac.ComputeHash(messageBytes);

this.hmac.Text=ByteToString(hashmessage);


}
public static string ByteToString(byte [] buff)
{
string sbinary="";

for (int i=0;i<buff.Length;i++)
{
sbinary+=buff[i].ToString("X2"); // hex format
}
return(sbinary);
}