Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

php md5 algorithm that gives same result as c#

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

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.

Upvotes: 8

Views: 5965

Answers (6)

d3nx
d3nx

Reputation: 11

it should be like as below for php

 php -r "echo base64_encode(md5(utf8_encode('asd'),true));"

Upvotes: 1

Kyle
Kyle

Reputation: 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))), “-”, “”);
}

Upvotes: -1

RRG
RRG

Reputation: 457

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

Upvotes: 0

Factor Mystic
Factor Mystic

Reputation: 26800

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#

Upvotes: 5

John Downey
John Downey

Reputation: 14114

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.

Upvotes: 20

driis
driis

Reputation: 164341

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

Upvotes: 4

Related Questions