If .net sha1 hash expects a byte array, and php sha1() wants a string, can I match the results?

StackOverflow https://stackoverflow.com/questions/616087

  •  03-07-2019
  •  | 
  •  

Question

I have a set of bytes I want to apply an sha1 hash to. One hash will be in .net, the other in PHP. Then I'll test to see if they match.

In .net, you can create a byte array and use sha.ComputeHash().

byte[] data = new byte[DATA_SIZE];
byte[] result; 

SHA1 sha = new SHA1CryptoServiceProvider(); 
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);

In PHP, you call sha1($string).

I can't do anything about the .net side of the code, but how can I get the same hash out of PHP that .net will generate?

Please note: I am ONLY able to work on the PHP side of this. The .net stuff is fixed and can't be modified. Thanks!

Was it helpful?

Solution

Since SHA1 is a common, standard algorithm, it is implemented the same way in PHP as it is in .NET. The only part that is different is how you invoke the two functions.

Technically, SHA1 is defined on bytes rather than strings, but (correct me if I'm wrong) PHP strings work with single-byte characters, so bytes and characters should be interchangable from the SHA1 algorithm's point of you.

You'll have to make sure that your string's value in binary is the same as .NET's byte array, in the same order. I'm not a PHP guy, so you'll have to get someone else's answer for how to do that.

OTHER TIPS

It looks like the sha1 function takes a byte array which is in hexidecimal notation. So if you had two bytes, FA and A1, your string would be "FAA1".

Then, you would parse the result string back into bytes and compare with the .NET output.

Note that you could create this string in .NET with the same format rather easily (use the "x2" format on the call to ToString on each byte and append all together).

This works for me:

string str = user.Salt + pepper + password;
SHA1 sha1 = new SHA1CryptoServiceProvider();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] input = encoder.GetBytes(str);
byte[] hash = sha1.ComputeHash(input);
string hashStr = "";
for (int i = 0; i < hash.Length; i++)
     hashStr += hash[i].ToString("X").ToLower();
if (hashStr != user.Hash)
     return false;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top