Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 hashing does not match in C# and PHP

Tags:

c#

php

md5

I have tried hashing a string in PHP using MD5 and the same in C#, but the results are different.. can someone explain me how to get this matched?

my C# code looks like

md5 = new MD5CryptoServiceProvider();             originalBytes = ASCIIEncoding.Default.GetBytes(AuthCode);             encodedBytes = md5.ComputeHash(originalBytes);              Guid r = new Guid(encodedBytes);             string hashString = r.ToString("N"); 

Thanks in advance

Edited: My string is 123 as a string

Outputs;

PHP: 202cb962ac59075b964b07152d234b70

C# : 62b92c2059ac5b07964b07152d234b70

like image 788
megazoid Avatar asked Apr 28 '11 16:04

megazoid


People also ask

What is the problem with MD5 hashing?

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 do you match MD5?

Type the following command: md5sum [type file name with extension here] [path of the file] -- NOTE: You can also drag the file to the terminal window instead of typing the full path. Hit the Enter key. You'll see the MD5 sum of the file. Match it against the original value.

Can MD5 be different?

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


2 Answers

Your problem is here:

Guid r = new Guid(encodedBytes); string hashString = r.ToString("N"); 

I'm not sure why you're loading your encoded bytes into a Guid, but that is not the correct way to convert bytes back to a string. Use BitConverter instead:

string testString = "123"; byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(testString); byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes); string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); // hashString == 202cb962ac59075b964b07152d234b70 
like image 168
Juliet Avatar answered Oct 03 '22 02:10

Juliet


The solution from Juliet didn't give me the same result as a PHP hash I was comparing against (produced by Magento 1.x), however the following did, based on this implementation on github:

                using (var md5 = MD5.Create())                 {                     result = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(input)))                         .Replace("-", string.Empty).ToLower();                 } 
like image 41
voxoid Avatar answered Oct 03 '22 02:10

voxoid