簡體   English   中英

制作JAVA MD5 hash匹配C# MD5 hash

[英]Make JAVA MD5 hash match C# MD5 hash

我的工作是重寫一堆 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 hash。但我無法理解的是我展示的部分。 我在 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 hash 字符串,但結果不同。

您顯示的兩個代碼片段之間的編碼有所不同 - 您的 Java 代碼使用 UTF-8,但您的 C# 代碼使用 ASCII。 這將導致不同的 MD5 hash 計算。

更改您的 C# 代碼:

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

到:

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

應該™ 解決您的問題,前提是沒有其他代碼轉換錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM