简体   繁体   中英

MD5 hashing does not match in C# and PHP

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

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

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();
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM