Why isn't my PHP SHA256 hash equivalent to C# SHA256Managed hash

Lemontongs picture Lemontongs · Aug 30, 2011 · Viewed 11.2k times · Source

Why aren't these the same?

php:

    $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );

c#

    public static string ComputeHash(string plainText, string salt)
    {
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        SHA256Managed hash = new SHA256Managed();

        // Compute hash value of salt.
        byte[] plainHash = hash.ComputeHash(plainTextBytes);

        byte[] concat = new byte[plainHash.Length + saltBytes.Length];

        System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
        System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);

        byte[] tHashBytes = hash.ComputeHash(concat);

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(tHashBytes);

        // Return the result.
        return hashValue;
    }

Answer

cwallenpoole picture cwallenpoole · Aug 30, 2011

C# is outputting a base64 ecoded string, and PHP is outputting a number in hex. A better comparison might be to pass the parameter true to the end of the hash function of PHP and base64 the result:

 $hash = base64_encode(
           hash('sha256', $userData['salt'] . hash('sha256', $password), true )
         );