有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使JAVA MD5哈希与C#MD5哈希匹配

我的工作是重写一堆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哈希字符串,但结果不同


共 (1) 个答案

  1. # 1 楼答案

    您所展示的两个代码片段在编码上存在差异——您的Java代码使用UTF-8,但您的C#代码使用ASCII。这将导致不同的MD5哈希计算

    将您的C#代码更改为:

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

    致:

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

    应该™ 修复您的问题,前提是没有其他代码转换错误