2013-02-17 110 views
1

我必須將C#哈希從下面的代碼複製到PHP中。我一直在尋找,但到目前爲止還沒有找到解決方案。將C#MD5哈希複製到PHP

this article on creating an md5 hash string

using System; 
using System.Text; 
using System.Security.Cryptography; 

// Create an md5 sum string of this string 
static public string GetMd5Sum(string str) 
{ 
    // First we need to convert the string into bytes, which 
    // means using a text encoder. 
    Encoder enc = System.Text.Encoding.Unicode.GetEncoder(); 

    // Create a buffer large enough to hold the string 
    byte[] unicodeText = new byte[str.Length * 2]; 
    enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true); 

    // Now that we have a byte array we can ask the CSP to hash it 
    MD5 md5 = new MD5CryptoServiceProvider(); 
    byte[] result = md5.ComputeHash(unicodeText); 

    // Build the final string by converting each byte 
    // into hex and appending it to a StringBuilder 
    StringBuilder sb = new StringBuilder(); 
    for (int i=0;i<result.Length;i++) 
    { 
     sb.Append(result[i].ToString("X2")); 
    } 

    // And return it 
    return sb.ToString(); 
} 

對於輸入= 「123」,上面的代碼給了我

我曾嘗試下面的PHP代碼,但它沒有給出相同的輸出 「5FA285E1BEBE0A6623E33AFC04A1FBD5」。

從SO質疑PHP MD5 not matching C# MD5

$str = "123"; 
$strUtf32 = mb_convert_encoding($str, "UTF-32LE"); 
echo md5($strUtf32); 

此代碼具有這樣的結果= 「a0d5c8a4d386f15284ec25fe1eeeb426」。順便說一下,將UTF-32LE更改爲utf-8或utf-16仍然不會給我相同的結果。

任何人都可以幫忙嗎?

+0

MD5是一個散列算法。除非他們改變了算法(他們爲什麼會這麼做?),它們計算的散列應該在兩個實現中都是相同的。 – 2013-02-17 03:56:02

+3

你的c#使用utf-16LE,你的php utf-32 – CodesInChaos 2013-02-17 03:57:29

+0

如果可以的話,兩邊都使用utf-8 – CodesInChaos 2013-02-17 04:01:36

回答

0

呃,C#代碼創建一個MD5哈希和PHP mb_convert_encoding功能只是編碼字符串...

另外,這是不是從你給的鏈接的完整代碼。這是因爲丟失了重要的MD5函數:

$str = "123"; 
$strUtf32 = mb_convert_encoding($str, "UTF-16"); 
echo md5($strUtf32); <===== 

如果代碼相匹配,應該沒有理由不應該工作,因爲MD5算法仍然是相同的,不因語言不同而不同。

2

是的,正如CodesInChaos所說,你的編碼錯了。

在PHP端試試這個:

$str = "123"; 
$strUtf32 = mb_convert_encoding($str, "UTF-16LE"); 
echo md5($strUtf32); 

這會給你5FA285E1BEBE0A6623E33AFC04A1FBD5。這將匹配c#端的System.Text.Encoding.Unicode

否則在c#端更改System.Text.Encoding.UnicodeSystem.Text.Encoding.UTF32。這會給你A0D5C8A4D386F15284EC25FE1EEEB426

+0

thx!有用 ! – Rex 2013-02-17 05:02:17

+0

@Rex請考慮接受答案,如果它解決了你的問題。 http://meta.stackexchange.com/a/5235/161449 – 2013-02-17 05:22:04