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

穆罕默德·拉贾比:

我的工作是用C#重写一堆Java代码。这是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哈希字符串,但结果却不同。

CoolBots:

显示的两个代码段之间的编码有所不同-Java代码使用UTF-8,而C#代码使用ASCII。这将导致不同的MD5哈希计算。

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

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

至:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章