Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert C# hashed byte array to string for passing to API?

Tags:

c#

hash

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!

like image 609
Sean Haddy Avatar asked Jan 06 '12 23:01

Sean Haddy


1 Answers

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.

like image 157
craig1231 Avatar answered Oct 12 '22 13:10

craig1231