Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

php

sha256

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;
    }
like image 924
Lemontongs Avatar asked Aug 30 '11 21:08

Lemontongs


1 Answers

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 )
         );
like image 182
cwallenpoole Avatar answered Sep 18 '22 15:09

cwallenpoole