gpt4 book ai didi

c# - 如何对 SHA-256 哈希进行十六进制编码

转载 作者:行者123 更新时间:2023-11-30 20:29:22 25 4
gpt4 key购买 nike

如何在 C# 中正确地对 SHA-256 哈希进行十六进制编码?

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

我这样做了,但结果与我使用的银行沙箱不同。

测试数据:

{"CorporateID":"BCAAPI2016","SourceAccountNumber":"0201245680","TransactionID":"00000001","TransactionDate":"2017-09-13","ReferenceID":"refID""CurrencyCode":"IDR","Amount":"10000","BeneficiaryAccountNumber":"0201245681","Remark1":"转账测试","Remark2":"在线转账"

银行的沙箱结果:e9d06986c1ed6b063bf59aa873030013725c518631deef2b2147e614017c2141

我的:1c83acc42cf905ca8afba27ef0640c70ad2856a366b57c17cf16f2894327676e

最佳答案

我见过这个问题的几种解决方案,但您的代码是最优雅的。我稍微重构了它并测试了它的答案。我也得到了哈希:

1c83acc42cf905ca8afba27ef0640c70ad2856a366b57c17cf16f2894327676e

在这里查看工作 fiddle :https://dotnetfiddle.net/QbsKTc

也许此哈希与银行的不同,因为您更改了 JSON 字符串以删除私有(private)数据?

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

关于c# - 如何对 SHA-256 哈希进行十六进制编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46194754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com