0

I am converting strings to MD5 hashes using c#. I am then converting strings to MD5 hashes using Java. I have noticed that the results are not the same, even for the same input strings.

Here is my Java Code:

public String encrypt(String message)
{
    String digest = null;
    try
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hash = md.digest(message.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder(2*hash.length);

        for(byte b : hash)
        {
            sb.append(String.format("%02x", b&0xff));
        }

        digest = sb.toString();
    }
    catch (Exception e)
    {
        //Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    }

    return digest;

}

}

Here is my C# Code:

public static string Encrypt(string input)
    {
        Byte[] inputBytes = Encoding.UTF8.GetBytes(input);

        Byte[] hashedBytes = new MD5CryptoServiceProvider().ComputeHash(inputBytes);

        return BitConverter.ToString(hashedBytes);
    }

I have easier access to the Java code. Is there any way I could modify the Java code such that the resultant hashes are the same as the C# hashes?

Thank you in advance.

user1162850
  • 101
  • 2
  • 10
  • 1
    I'd check the actual bytes being output by both decoders. Make sure you don't have a BOM in there...things get weird when they get involved. :P – cHao Aug 18 '13 at 06:36
  • 1
    [This](http://stackoverflow.com/questions/2920044/how-can-you-generate-the-same-md5-hashcode-in-c-sharp-and-java) should help you.. – Vikas V Aug 18 '13 at 06:36

2 Answers2

2

They both produce the same result, but the output string format is different

Java: 264fcf838c8e4b9d17c510cd5b8b9b78
C#: 26-4F-CF-83-8C-8E-4B-9D-17-C5-10-CD-5B-8B-9B-78

Simplest on the Java side is to just rework your loop slightly to add the dashes and upper case hex BitConverter.ToString() adds;

boolean add_dash = false;
for(byte b : hash)
{
    if(add_dash)
        sb.append("-");
    add_dash = true;
    sb.append(String.format("%02X", b&0xff));
}

That will make both produce the MD5 sum in the format

26-4F-CF-83-8C-8E-4B-9D-17-C5-10-CD-5B-8B-9B-78

It's simpler to do the reverse on the C# side, just change your return to;

return BitConverter.ToString (hashedBytes).Replace("-", "").ToLowerInvariant();
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

I believe this is the answer you are looking for:

StringBuilder hexString = new StringBuilder() 
for (byte b: hash) {
    String hex = Integer.toHexString(b & 0xFF);
    if (hex.length() == 1) {
        hexString.append("0");
    }
    hexString.append(hex.toUpperCase());
    hexString.append("-");
}

The hexString.toString() should produce the same result as BitConverter.ToString(byte[]) method.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228