Outputting A SHA256 Hash in Hex in .NET Framework
[C#, .NET, Hashing]
Obtaining a SHA256 hash in C# & .NET is a pretty trivial exercise.
You call the HashData method of the SHA256 class as follows:
SHA256.HashData(Encoding.UTF8.GetBytes("Rainbows"))
This will give you an array of bytes.
Typically, you want this in a human-readable string.
A quick way to do so is to use the ToHex method of the Convert class.
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("Rainbows"))
If we output this, we get the following:
89C39E5BD3FF61EC26E432F0F576E7416C66FF7BF9E133E3C0776DCBE1477ED6
Recently, I needed to implement this in a legacy .NET Framework application.
Hashing is slightly different there.
You do it like this:
SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("Rainbows")
Getting the byte array as a string is more of a challenge, as there is no ToHex method in the .NET Frameworkâs Convert class.
Thankfully, writing one is trivial.
public static class ByteArrayExtensions
{
public static string ToHexString(this byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
// Get the Hex letter values in upper case
sb.Append(b.ToString("X2"));
return sb.ToString();
}
}
Here, I have implemented it as an extension method.
I can then use it like this:
SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("Rainbows")).ToHexString()
This gives me the same result as before:
89C39E5BD3FF61EC26E432F0F576E7416C66FF7BF9E133E3C0776DCBE1477ED6
TLDR
You can convert a byte array to a hex string on .NET Framework by writing a simple extension method.
The code is in my GitHub.
Happy hacking!