tags:

views:

1196

answers:

4

Hello, i have a hashing algorithm in C#, in a nutshell, it is:

string input = "asd";

System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();


byte[] hash = alg.ComputeHash(enc.GetBytes(input));
string output = Convert.ToBase64String(hash);

// outputs:   eBVpbsvxyW5olLd5RW0zDg==
Console.WriteLine(output);

Now I need to replicate this behaviour in php,

$input = "asd";
$output = HashSomething($input);
echo $output;

How can I achieve it?

I checked

  • md5
  • utf8_decode
  • utf8_encode
  • base64_encode
  • base64_decode
  • url_decode

but i noted the php md5 doesn't get the == on the end... what am I missing?

NOTE: I cannot change C# behaviour because it's already implemented and passwords saved in my db with this algorithm.

+5  A: 

Did you remember to base64 encode the md5 hash in php?

$result = base64_encode(md5($password, true));

The second parameter makes md5 return raw output, which is the same as the functions you're using in C#

Factor Mystic
Darn. You bet me... The == is usually from the Base64 encoding, you are doing with Convert.ToBase64String() is that what you are missing?
David McEwing
Wow. Totally missed that line in the C# code.
Thomas Owens
Yeah, but how can I achieve it on php? what function should I use?
Jhonny D. Cano -Leftware-
+3  A: 

Your C# code takes the UTF8 bytes from the string; calculates md5 and stores as base64 encoded. So you should do the same in php, which should be:

$hashValue = base64_encode(md5(utf8_decode($inputString)))
driis
+14  A: 

The issue is PHP's md5() function by default returns the hex variation of the hash where C# is returning the raw byte output that must then be made text safe with base64 encoding. If you are running PHP5 you can use base64_encode(md5('asd', true)). Notice the second parameter to md5() is true which makes md5() return the raw bytes instead of the hex.

John Downey
The true flag for md5 only exists in PHP5 or higher. In earlier versions you would need to call the pack function.
jmucchiello
A: 

I had the same issue...using just md5($myvar) it worked. I am getting the same result C# and PHP.

Argyris