Sam Alekseev
Sam Alekseev

Reputation: 2391

Different MD5 hashes in PHP and C#

Why hashes become different if i change input string?

My C# code is:

public static string CreateMD5(string strInput)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(strInput);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            string hashedString = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
            return hashedString;
        }
    }

In PHP I use the md5() function. It is an online service so I have no source code; I just use that website to match results.

If I have this string:

test-server::7250406f7c43524545f794ff50dfd15b

Hashes are the same: 20202421c846813960404af7dd36c146. But if I extend the string to this (with encoded characters):

test-server::7250406f7c43524545f794ff50dfd15b::name=%D0%98%D0%BD%D0%B5%D1%81%D1%81%D0%B0

Now hashes are different: 3db825e09eae0a83db535fda7f5ee5b5 and ee1ae334e4bdeceb54caab15555f2f40.

Why this happening?

Upvotes: 0

Views: 627

Answers (1)

user3783243
user3783243

Reputation: 5223

The hash value ee1ae334e4bdeceb54caab15555f2f40 is the MD5 hash over test-server::7250406f7c43524545f794ff50dfd15b::name=Инесса. This input is the URL-decoded version of test-server::7250406f7c43524545f794ff50dfd15b::name=%D0%98%D0%BD%D0%B5%D1%81%D1%81%D0%B0.

Your C# code fragment performs MD5 on the non-decoded version. PHP decodes GETs by default so to get the same result you will need to double encode the value being set to the PHP script.

See here, https://3v4l.org/rK7fi (online PHP code implementation):

The GET variables are passed through urldecode().

http://php.net/manual/en/reserved.variables.get.php

Alternatively if you MD5 the value before you URL encode the values in the C# the systems should return the same hash.

Upvotes: 4

Related Questions