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

后端 未结 6 2002
灰色年华
灰色年华 2020-12-20 12:14

Why aren\'t these the same?

php:

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

c#



        
相关标签:
6条回答
  • 2020-12-20 12:23

    Well I'm no C# programmer, but one thing that leaps out at me is this:

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

    Are you base64-encoding the final output in C#? Because you're not in PHP...

    0 讨论(0)
  • 2020-12-20 12:24

    First suspect:

    Encoding.UTF8.GetBytes(plainText);
    

    C# uses UTF-8, your PHP probably doesn't, but you could be lucky if you use strictly letters from the US-ASCII subset.

    Second suspect:

    Convert.ToBase64String(tHashBytes);
    

    There's nothing about Base64 in your PHP.

    Since PHP will give you a hex-encoded result, you should switch to Hex in your C#, too. See this answer for solutions.

    0 讨论(0)
  • 2020-12-20 12:35
    C#
    string toHash = "abcdefg";
    SHA256Managed hash = new SHA256Managed();
    byte[] signatureData = hash.ComputeHash(new UnicodeEncoding().GetBytes(toHash));
    string hashResult = System.Convert.ToBase64String(signatureData);
    PHP
    print base64_encode(hash("sha256",mb_convert_encoding("abcdefg","UTF-16LE"),true));
    

    Write like top code,They are the same

    0 讨论(0)
  • 2020-12-20 12:35

    C#

    string toHash = "abcdefg"; 
    SHA256Managed hash = new SHA256Managed(); 
    byte[] signatureData = hash.ComputeHash(new UnicodeEncoding().GetBytes(toHash)); 
    string hashResult = System.Convert.ToBase64String(signatureData); 
    

    PHP

    print base64_encode(hash("sha256",mb_convert_encoding("abcdefg","UTF-16LE"),true));
    

    Works for me.

    0 讨论(0)
  • 2020-12-20 12:42

    Because they're different. Your C# code encodes the computed hash in Base64 encoding at the end. PHP just returns a string of hexadecimal digits.

    0 讨论(0)
  • 2020-12-20 12:43

    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 )
             );
    
    0 讨论(0)
提交回复
热议问题