【问题标题】:Make JAVA MD5 hash match C# MD5 hash使 JAVA MD5 哈希匹配 C# MD5 哈希
【发布时间】:2020-12-08 00:03:57
【问题描述】:

我的工作是重写一堆Java代码是C#。 这是JAVA代码:

        public static String CreateMD5(String str) {
    try {
        byte[] digest = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
        StringBuffer stringBuffer = new StringBuffer();
        for (byte b : digest) {
    // i can not understand here
            stringBuffer.append(Integer.toHexString((b & 255) | 256).substring(1, 3));
        }
        return stringBuffer.toString();
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException unused) {
        return null;
    }
}

好的。正如你所看到的,这段代码试图使 MD5 散列。但我无法理解的是我展示的部分。 我在 C# 中尝试了这段代码来重写这段 JAVA 代码:

    public static string CreateMD5(string input)
    {
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hashBytes = md5.ComputeHash(inputBytes);

    // Convert the byte array to hexadecimal string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hashBytes.Length; i++)
    {
        sb.Append(hashBytes[i].ToString("X2"));
    }
    return sb.ToString();
}
    }

这两个代码都在生成 MD5 哈希字符串,但结果不同。

【问题讨论】:

    标签: java c# hash md5


    【解决方案1】:

    您显示的两个代码 sn-ps 之间的编码存在差异 - 您的 Java 代码使用 UTF-8,但您的 C# 代码使用 ASCII。这将导致不同的 MD5 哈希计算。

    从以下位置更改您的 C# 代码:

    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    

    到:

    byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
    

    如果没有其他代码转换错误,这应该™解决您的问题。

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2019-10-10
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2011-05-29
      • 1970-01-01
      相关资源
      最近更新 更多