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

谁都会走 提交于 2019-11-29 13:14:00

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 )
         );

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.

emboss

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.

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...

lei.liu
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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!