简体   繁体   中英

C# SHA256 Hashing

Below is the code I use for hashing and I am trying to store the hash in a string(strSHA256) with UTF-8 encoding.

using (SHA256 sha256Hash = SHA256.Create())
{
   bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(utf8EncodedString));
   strSHA256 = Encoding.UTF8.GetString(bytes);               
}

When I inspect the string variable I see " u Ou\ O zA \ \\0 \\a }\ L Dr " type of value. My question is regarding to ? character marked in bold. They should be UTF-8 chars. Why cant I view the UTF-8 special chars when I inspect from visual studio. The string o/p contains this weird char as well.

Note: I tried SHA256 with Node Js and I tend to see perfect UTF-8 special chars.

As @user2864740 mentioned bytes are not UTF8. Use base64 for bytes string representation.

       var hello = "Hello world!";
        using (var sha256Hash = SHA256.Create())
        {
            var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(hello));

            // String representation
            var stringForBytes  = Convert.ToBase64String(bytes);

            // HEX string representation
            var str = new StringBuilder(bytes.Length * 2);
            foreach (var b in bytes)
            {
                str.Append(b.ToString("X2"));
            }

            var hexString = str.ToString();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM