1

I'm trying to get a C# Sha1 hash in PHP. The C# code was handed to me, it appears to use ASCIIEncoding which from what I read is what PHP uses. Not sure what is wrong. Any tips are appreciated.

C# code:

byte[] data = Encoding.ASCII.GetBytes(text);
byte[] HashValue; 
SHA1Managed SHhash = new SHA1Managed();
hashValue = SHhash.ComputeHash(data);
foreach (byte b in hashValue)
{
    sha1string += String.Format("{0:x2}", b);
}
return sha1string;

PHP Code:

return sha1(text);

The output:

C#  : 5f10f7410406cdab11f3c44fe8c634718eb68e98
PHP : bba18b9b35c440c25b8dcf2efb973d86ee1442e2
Dai
  • 141,631
  • 28
  • 261
  • 374
zeros-and-ones
  • 4,227
  • 6
  • 35
  • 54
  • 1
    so what does `text` look like in php, v.s. what's in `data` in c#? even one single BIT different in any of the individual bytes will completely throw off the hash. e.g. maybe one's got a newline you didn't account for. – Marc B Sep 01 '15 at 21:56
  • thats what i was thinking. I wanted to make sure that i was correct first. i'm waiting to hear back, the string I have contains a public email so I can't post it on here. – zeros-and-ones Sep 01 '15 at 21:58
  • well, you can always test it with some other string. doesn't have to be your private data. if it's failing on one string, it'll probably fail similarly on any other string. – Marc B Sep 01 '15 at 21:59
  • 2
    Most likely an encoding mismatch. PHP treats strings as sequences of bytes, but those can differ for seemingly identical strings depending on what encoding is used to save the script. For instance, `sha('é')` will produce two completely different hashes if saved as ISO-8859-1 (where é is `e9`) vs. UTF-8 (`c3a9`). – lafor Sep 01 '15 at 22:30
  • You can use a dummy email address. No need to use a real one but it is quite useful omho to know what `text` looks like. – rbaleksandar Sep 01 '15 at 22:36
  • http://stackoverflow.com/questions/790232/c-sharp-sha-1-vs-php-sha-1-different-results – Afshin Arani Sep 05 '15 at 13:38
  • The hash algorithms matched up, the data provided was incorrect. – zeros-and-ones Sep 22 '15 at 22:38

0 Answers0