-2

I don't know if it's a "spec" or generally agreed upon or linux or just google, but many sites say that the SHA256 hash for an empty string is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 or base64 "ZTNiMGM0NDI5OGZjMWMxNDlhZmJmNGM4OTk2ZmI5MjQyN2FlNDFlNDY0OWI5MzRjYTQ5NTk5MWI3ODUyYjg1NQ=="

However, given the following code in C#

    using (var sha256 = SHA256.Create())
    {
        var contentBytes = System.Text.Encoding.UTF8.GetBytes(content);
        byte[] hashedBytes = sha256.ComputeHash(contentBytes);
        var hash = Convert.ToBase64String(hashedBytes);
        return hash;
    }

the base64 value of hash where content=string.empty or content="" will be "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="

Why the difference?

WirelessG
  • 227
  • 2
  • 11
  • That base64 string cannot be equivalent to that hex, as the base64 is longer (and should be shorter). The base64 of SHA256(empty) is `47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=` – Richard Heap May 18 '23 at 00:55
  • 1
    In the first part you have base64 encoded the **hex** value rather than the binary value. Both examples produce the same hash `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. – President James K. Polk May 18 '23 at 00:55
  • 1
    Since this question is based on misinterpretation of strings and byte arrays and unrelated to title at all, I voted to close as "typo"... Consider reading https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa which may help to clarify things (along with the answer posted here). – Alexei Levenkov May 18 '23 at 02:31

1 Answers1

1

You're most likely seeing a BOM being emitted from the UTF8 encoder.

Edit: Maybe not. This works for me:

var content = string.Empty;
using (var sha256 = SHA256.Create())
{
    var contentBytes = System.Text.Encoding.UTF8.GetBytes(content);
    byte[] hashedBytes = sha256.ComputeHash(contentBytes);
    Console.WriteLine(BitConverter.ToString(hashedBytes).Replace("-","").ToLowerInvariant());
}

Output:

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

The "ZTNiMG..." is the Base64 representation of the string "e3b0c..." and not the bytes e3 b0 c4.... So the "47DEQ..." is actually correct.

If you insist on the "ZTNiMG..." string then use this:

var content = string.Empty;
using (var sha256 = SHA256.Create())
{
    var contentBytes = System.Text.Encoding.UTF8.GetBytes(content);
    byte[] hashedBytes = sha256.ComputeHash(contentBytes);
    Console.WriteLine(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(BitConverter.ToString(hashedBytes).Replace("-","").ToLowerInvariant())));
}

Output: ZTNiMGM0NDI5OGZjMWMxNDlhZmJmNGM4OTk2ZmI5MjQyN2FlNDFlNDY0OWI5MzRjYTQ5NTk5MWI3ODUyYjg1NQ==

RobIII
  • 8,488
  • 2
  • 43
  • 93