2011-04-28 84 views
20

我曾嘗試使用MD5在PHP中使用MD5散列字符串,並且在C#中使用相同的結果,但結果不同..有人可以解釋我如何獲得匹配嗎?MD5 hashing在C#和PHP中不匹配

我的C#代碼看起來提前

編輯像

md5 = new MD5CryptoServiceProvider(); 
      originalBytes = ASCIIEncoding.Default.GetBytes(AuthCode); 
      encodedBytes = md5.ComputeHash(originalBytes); 

      Guid r = new Guid(encodedBytes); 
      string hashString = r.ToString("N"); 

感謝:我的字符串是123爲字符串

輸出;

PHP:202cb962ac59075b964b07152d234b70

C#:62b92c2059ac5b07964b07152d234b70

+0

您沒有向我們展示您嘗試使用的字符串或您嘗試使用的PHP代碼。 – 2011-04-28 16:11:26

+0

你在這裏輸入了什麼?什麼是您的等效PHP代碼? – 2011-04-28 16:12:19

+0

http://stackoverflow.com/questions/821817/php-md5-algorithm-that-gives-same-result-as-c/821846#821846 – 2011-04-28 16:13:02

回答

31

你的問題是在這裏:

Guid r = new Guid(encodedBytes); 
string hashString = r.ToString("N"); 

我不知道爲什麼你加載你的編碼的字節轉化爲GUID,但是這是不是將字節轉換回字符串的正確方法。改爲使用BitConverter

string testString = "123"; 
byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(testString); 
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes); 
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); 
// hashString == 202cb962ac59075b964b07152d234b70 
+2

朱麗葉......完美!!!!感謝百萬隊友! – megazoid 2011-04-30 15:11:44