How to Hex Encode a SHA-256 Hash

ε祈祈猫儿з 提交于 2019-12-11 03:25:12

问题


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


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/46194754/how-to-hex-encode-a-sha-256-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!