8

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.

Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103

6 Answers6

20

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
  • 13,854
  • 5
  • 37
  • 33
  • 4
    The true flag for md5 only exists in PHP5 or higher. In earlier versions you would need to call the pack function. – jmucchiello May 04 '09 at 20:57
5

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
  • 26,279
  • 16
  • 79
  • 95
4

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
  • 161,458
  • 45
  • 265
  • 341
1

it should be like as below for php

 php -r "echo base64_encode(md5(utf8_encode('asd'),true));"
Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
d3nx
  • 11
  • 1
0

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

RRG
  • 457
  • 5
  • 18
-1

Gavin Kendall posted helped me. I hope this helps others.

http://jachman.wordpress.com/2006/06/06/md5-hash-keys-with-c/

public static string MD5Hash(string text)
{
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), “-”, “”);
}
shanethehat
  • 15,460
  • 11
  • 57
  • 87
Kyle
  • 1