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

2

6

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;
    }
Scammony answered 1/7, 2015 at 19:28 Comment(2)
Please don't use SHA256 hashes to store passwords (assuming you're designing this from scratch). Please read up on modern methods of storing passwords, you should use something like this: msdn.microsoft.com/en-us/library/… or some other multi-iteration method.Boccioni
Thanks for the link. We're using SHA256, backend is salting unique to user, and we are not double hashing. Looks like an improvement we can make is to use PBKDF2 instead of SHA256.Scammony
S
13

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.

Sentiment answered 1/7, 2015 at 19:32 Comment(0)
D
0

After computing the hash using Encoding.UTF8 as stated on the answer above, I would also return a string as follows:

 hex = BitConverter.ToString(hashValue).Replace("-", "");

 return hex;
Duleba answered 23/2, 2023 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.