开发者

C# equivalent to Java's DigestUtils.md5Hex(String)?

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 m开发者_开发技巧inimum, 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.


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


I found this code in HashAlgorithm.ComputeHash, and check with my friend who develop in Java, it works.

public static string MD5Hex(string input)
{
    byte[] bytes = Encoding.UTF8.GetBytes(input);
    MD5 md5 = MD5.Create(); // or MD5CryptoServiceProvider
    byte[] result = md5.ComputeHash(bytes);

    var stringBuilder = new StringBuilder();
    for (int i = 0; i < result.Length; i++)
    {
        stringBuilder.Append(result[i].ToString("x2"));
    }

    return stringBuilder.ToString();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜