tags:

views:

440

answers:

1

Is there a ready-made C# equivalent to Java's DigestUtils.md5Hex(String)? My Java is rusty, but I can say that DigestUtils is part of the Apache Commons Codec package, and the md5Hex(String) method essentially uses MessageDigest.getInstance("MD5").

(One related tidbit, both the Java and C# code are using UTF8.)


In the simplest of tests, I have ruled out any difference between the Java and C# algorithms I'm using. This means my problem is elsewhere. But, for the record, these two piece of code generate identical results: (Thanks, Alex.)

Java:

private static void printMd5Hex(String data) {
    System.out.println(DigestUtils.md5Hex(data));
}

C#:

private static void printMd5Hex(string data)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] dataHash = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    StringBuilder sb = new StringBuilder();
    foreach (byte b in dataHash)
    {
        sb.Append(b.ToString("x2").ToLower());
    }
    Console.WriteLine(sb.ToString());
}


For proper closure on this question, the root of my problem had to do with a bug in the Java code in the format string used to create the "data" being hashed. In essence:

string dataFormatString = "%1$s, %2$s, %3$s, %4$s, %5$s, %6$s, %7$s, %8$s, %9$s, %10$s, %11$s, %12s";
string dataToHash = String.Format(dataFormatString, ...);

The problem is that 12th parameter. It's missing a $, which means the data is space-padded to 12 characters minimum, using the first argument as the data to format. Sadly, the dev who wrote the bug doesn't work here anymore, thus robbing me of the chance to wrap my hands around his throat.

+2  A: 

Do you want to calculate md5 in c#?

System.Security.Cryptography.MD5CryptoServiceProvider x =
    new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
   s.Append(b.ToString("x2").ToLower());
}
password = s.ToString();
Alex Reitbort
Thanks @Alex and/or jitter. I can, and have, successfully calculated md5 in C#, using the "System.Security.Cryptography.MD5" hash algorthim. However, something about the way I'm attempting to replicate DigestUtils.md5Hex(String) behaviour is not resulting in the same hash. I'm going to give this a try.
JMD
I have now tried the method above, with MD5CryptoServiceProvider.ComputeHash(byte[]), and it is with mixed emotion that I report it generates the exact same hash as my existing code. Unfortunately, it doesn't match the output of DigestUtils.md5hex(String).
JMD
This example calculates md5 on UTF8 encoding of string. May be you need to use Unicode?
Alex Reitbort
DigestUtils has method to calculate md5 on byte[]. Same as .Net md5 provider. Run them on the same input and compare the output to see if the problem is in the provider or in converting string into bytes.
Alex Reitbort