使java md5哈希与c#md5哈希匹配

0lvr5msh  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(404)

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

wr98u20j

wr98u20j1#

您所展示的两个代码片段在编码上存在差异—java代码使用utf-8,而c代码使用ascii。这将导致不同的md5哈希计算。
将c代码更改为:

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

收件人:

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

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

相关问题