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

可紊 提交于 2019-12-23 09:56:57

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/8766038/how-to-convert-c-sharp-hashed-byte-array-to-string-for-passing-to-api

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