Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA256 hash of String in C# does not agree with hash on website

Tags:

c#

hash

sha256

If I hash the string "password" in C# using SHA256 using the below method I get this as my output:

e201065d0554652615c320c00a1d5bc8edca469d72c2790e24152d0c1e2b6189

But this website(SHA-256 produces a 256-bit (32-byte) hash value) tells me the has is:

5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

I'm clearly having a data format issue or something similar. Any ideas why this C# SHA256Managed method is returning something different? I'm sending the method "password" as the input parameter.

    private static string CalculateSHA256Hash(string text)
    {
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(text);

        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }
like image 964
LampShade Avatar asked Jul 01 '15 19:07

LampShade


1 Answers

UnicodeEncoding is UTF-16, guaranteed to inflate all your characters to two to four bytes to represent their Unicode code point (see also the Remarks section on MSDN).

Use (the static) Encoding.UTF8 instead, so most characters will fit in one byte. It depends on which system you need to mimic whether that will work for all strings.

like image 60
CodeCaster Avatar answered Nov 14 '22 21:11

CodeCaster