Create HMAC in C#

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Security.Cryptography;
protected void createHMACSHA()
        string message = "Hello";
        string key = "special encryption code";
        string hmac1,hmac2,hmac3,hmac4;
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        byte[] keyByte = encoding.GetBytes(key);
        byte[] messageBytes = encoding.GetBytes(message);
        HMACSHA1 hmacsha1     = new HMACSHA1(keyByte);
        HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
        HMACSHA384 hmacsha384 = new HMACSHA384(keyByte);
        HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);
        hmac1 = ByteToString(hashmessage);
        hashmessage = hmacsha1.ComputeHash(messageBytes);
        hmac2 = ByteToString(hashmessage);
        hashmessage = hmacsha256.ComputeHash(messageBytes);
        hmac3 = ByteToString(hashmessage);
        hashmessage = hmacsha384.ComputeHash(messageBytes);
        hmac4 = ByteToString(hashmessage);
        hashmessage = hmacsha512.ComputeHash(messageBytes);
private static string ByteToString(byte[] buff)
 string sbinary = "";

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


Add yours →

  1. what’s value for hashmessage? string, HMACSHA512, byte[]?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: