How to convert C# hashed byte array to string for

2019-06-23 16:47发布

I have a number of values that must be combined into a SHA256 hash to be passed to a web service. These values are combined into a byte array using Encoding.ASCII.GetBytes(allparametershere) and then hashed to SHA256 by myHashMethod.ComputeHash(allParameterByteArray). Since I have to add this value to a request header, it must be passed as a string to the request header.

The requirements of the 3rd party system state that it must be in 64 character Hex format of the string. I've used Convert.Base64String in the past, but I assume that's not what they are looking for as I only get errors when passing such a string. Any ideas?

Thanks!

标签: c# hash
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-23 17:03

This will give you the result in uppercase Hex, change X to x to make little case.

Change SHA256Result to be your result of the SHA256 Hash.

byte[] SHA256Result;
StringBuilder stringBuilder = new StringBuilder();

foreach(byte b in SHA256Result)
    stringBuilder.AppendFormat("{0:X2}", b);

string hashString = stringBuilder.ToString();

The resultant string is hashString and should have length 64, baring in mind SHA256Result is 32 bytes.

查看更多
登录 后发表回答