Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php md5 algorithm that gives same result as c#

Tags:

c#

php

md5

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.

like image 502
Jhonny D. Cano -Leftware- Avatar asked May 04 '09 20:05

Jhonny D. Cano -Leftware-


People also ask

Do MD5 and SHA 1 generate the same hash value if given the same input?

Yes, a hash algorithm always produces the same output.

Can MD5 hashes be the same?

Generally, two files can have the same md5 hash only if their contents are exactly the same. Even a single bit of variation will generate a completely different hash value. There is one caveat, though: An md5 sum is 128 bits (16 bytes).

Why you should not use MD5?

A major concern with MD5 is the potential it has for message collisions when message hash codes are inadvertently duplicated. MD5 hash code strings also are limited to 128 bits. This makes them easier to breach than other hash code algorithms that followed.

How does MD5 work in PHP?

The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input.


2 Answers

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.

like image 162
John Downey Avatar answered Sep 29 '22 07:09

John Downey


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#

like image 26
Factor Mystic Avatar answered Sep 29 '22 08:09

Factor Mystic