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);
        //HMACSHA1
        hmac1 = ByteToString(hashmessage);
        hashmessage = hmacsha1.ComputeHash(messageBytes);
       
        //HMACSHA256
        hmac2 = ByteToString(hashmessage);
        hashmessage = hmacsha256.ComputeHash(messageBytes);
       
        //HMACSHA384
        hmac3 = ByteToString(hashmessage);
        hashmessage = hmacsha384.ComputeHash(messageBytes);
       
        //HMACSHA512
        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);
 }
Advertisements

2 Comments

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: