Encrypts the keyvalue pair supplied using HMAC-MD5 - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:MD5

Description

Encrypts the keyvalue pair supplied using HMAC-MD5

Demo Code


using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w  w w .  j  a  v  a2s  . c  om*/

public class Main{
        /// <summary>
        /// Encrypts the key/value pair supplied using HMAC-MD5
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns></returns>
        public static string EncryptHMAC(string key, string value) {
            // The first two lines take the input values and convert them from strings to Byte arrays
            byte[] HMACkey = (new System.Text.ASCIIEncoding()).GetBytes(key);
            byte[] HMACdata = (new System.Text.ASCIIEncoding()).GetBytes(value);

            // create a HMACMD5 object with the key set
            HMACMD5 myhmacMD5 = new HMACMD5(HMACkey);

            //calculate the hash (returns a byte array)
            byte[] HMAChash = myhmacMD5.ComputeHash(HMACdata);

            //loop through the byte array and add append each piece to a string to obtain a hash string
            string fingerprint = "";
            for (int i = 0; i < HMAChash.Length; i++) {
                fingerprint += HMAChash[i].ToString("x").PadLeft(2, '0');
            }

            return fingerprint;
        }
}

Related Tutorials