6

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!

0

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't you use a StringBuilder and AppendFormat() instead?
Thank you. It worked for me. It compares fine correctly against the result from 7-Zip.
Why do you use the 2 in stringBuilder.AppendFormat("{0:X2}", b);?
@ElFik , The 2 means to specify 2 characters for each byte. With just X, 10 in decimal would be represented by A, whereas X2 would represent 10 as 0A. The upper case X, signifies upper case hexadecimal, and lower case X signifies lower case hexadecimal. learn.microsoft.com/en-us/dotnet/standard/base-types/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.