Calculating HMACSHA256 using c#

Hi, Recently I was working on the Calculating HMACSHA256 using c# in PayByWay Payment Gateway. This payment gateway required the HMACSHA256 encryption and decryption.

I spend many hours but didn’t get proper solution, At last I got the following code and did some customization as per my requirement and it works for me.

Here the code


using System;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace CustomHelperMvc.Helpers
{
    public class HMACSHA_256
    {
   
        public static string CalcHMACSHA256Hash()
        {
            string text = "0|12345|1|100123";
            string key = "xad3b23s2a0d0328b4ea08yd95";
            string reqCode = "BF7A74A6199D47C5C62176023686EE342BF5D608466F609348297B19278CF8A6";
            string result = string.Empty;
            var encode = Encoding.Default;
            byte[]
            hashed = encode.GetBytes(text),
            salt = encode.GetBytes(key);
            HMACSHA256 hasher = new HMACSHA256(salt);
            byte[] byteHashedText = hasher.ComputeHash(hashed);
            result = string.Join("", byteHashedText.ToList().Select(b => b.ToString("X2")).ToArray());
            return result;
        }
    }
}

In the above given example i have passed the text and key values as per my requirement and the reqCode should be the output or return value after the encryption. In my case the result and reqCode were same.

Happy Coding….

Posted by | View Post | View Group