tags:

views:

852

answers:

3

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!

+1  A: 

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

casperOne
+3  A: 

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.

Welbog
Once again, great suggestion. I'll get my .net guy to send me an example of the data that gets sent to the ComputeHash function to see if I can convert the PHP to it.
lynn
You accepted my answer again. Did you find out what was wrong?
Welbog
I finally did. The .net side is creating a keyed hash, so I needed to use hash_hmac() with a validation key on my side.
lynn
Aha! Congratulations!
Welbog
A: 

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