Search code examples
c#hexencodesha256sha

How to Hex Encode a SHA-256 Hash


How to Hex Encode a SHA-256 hash properly in C#?

private static string ToHex(byte[] bytes, bool upperCase)
{
    StringBuilder result = new StringBuilder(bytes.Length * 2);

    for (int i = 0; i < bytes.Length; i++)
        result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));

    return result.ToString();
}

private string hashRequestBody(string reqBody)
{
    string hashString;
    using (var sha256 = SHA256Managed.Create())
    {
        var hash = sha256.ComputeHash(Encoding.Default.GetBytes(reqBody));
        hashString = ToHex(hash, false);
    }

    MessageBox.Show(hashString);
    return hashString;
}

I did this, but the result is different with bank's sandbox I worked with.

TEST DATA:

{"CorporateID":"BCAAPI2016","SourceAccountNumber":"0201245680","TransactionID":"00000001","TransactionDate":"2017-09-13","ReferenceID":"refID","CurrencyCode":"IDR","Amount":"10000","BeneficiaryAccountNumber":"0201245681","Remark1":"Transfer Test","Remark2":"Online Transfer"}

Bank's sandbox result: e9d06986c1ed6b063bf59aa873030013725c518631deef2b2147e614017c2141

Mine: 1c83acc42cf905ca8afba27ef0640c70ad2856a366b57c17cf16f2894327676e


Solution

  • I've seen several solutions to this problem, but your code is the most elegant. I slightly re-factored it and tested it for this answer. I also get the hash:

    1c83acc42cf905ca8afba27ef0640c70ad2856a366b57c17cf16f2894327676e

    See working fiddle here: https://dotnetfiddle.net/QbsKTc

    Perhaps this hash is different to the bank's because you changed the JSON string to remove private data?

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(SHA256HexHashString("{\"CorporateID\":\"BCAAPI2016\",\"SourceAccountNumber\":\"0201245680\",\"TransactionID\":\"00000001\",\"TransactionDate\":\"2017-09-13\",\"ReferenceID\":\"refID\",\"CurrencyCode\":\"IDR\",\"Amount\":\"10000\",\"BeneficiaryAccountNumber\":\"0201245681\",\"Remark1\":\"Transfer Test\",\"Remark2\":\"Online Transfer\"}"));
        }
    
        private static string ToHex(byte[] bytes, bool upperCase)
        {
            StringBuilder result = new StringBuilder(bytes.Length * 2);
            for (int i = 0; i < bytes.Length; i++)
                result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));
            return result.ToString();
        }
    
        private static string SHA256HexHashString(string StringIn)
        {
            string hashString;
            using (var sha256 = SHA256Managed.Create())
            {
                var hash = sha256.ComputeHash(Encoding.Default.GetBytes(StringIn));
                hashString = ToHex(hash, false);
            }
    
            return hashString;
        }
    }