2013-06-27 129 views
0

我對此有點瘋狂!我試圖對現有數據庫驗證我的應用程序(所以我不能更改PHP端),我需要將我的密碼字段轉換爲與php的md5(moo)命令相同。c#md5與PHP md5 hash相同

但是,我嘗試創建散列的每個公式都會出現與md5相同的數據庫,它與數據庫中的數據非常不同。

是否有一個公式可以產生相同的結果?

我已經試過:

public static string MbelcherEncodePassword(string originalPassword) 
     { 
      Byte[] originalBytes; 
      Byte[] encodedBytes; 
      MD5 md5; 

      // Conver the original password to bytes; then create the hash 
      md5 = new MD5CryptoServiceProvider(); 
      originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword); 
      encodedBytes = md5.ComputeHash(originalBytes); 

      // Bytes to string 
      return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(encodedBytes), "-", "").ToLower(); 


     } 

和:

public static string MD5(string password) 
     { 
      byte[] textBytes = System.Text.Encoding.Default.GetBytes(password); 
      try 
      { 
       System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler; 
       cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
       byte[] hash = cryptHandler.ComputeHash(textBytes); 
       string ret = ""; 
       foreach (byte a in hash) 
       { 
        if (a < 16) 
         ret += "0" + a.ToString("x"); 
        else 
         ret += a.ToString("x"); 
       } 
       return ret; 
      } 
      catch 
      { 
       throw; 
      } 
     } 

和:

public static string MD5Hash(string text) 
      { 
       System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
       return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), "-", ""); 
      } 

無濟於事。任何幫助真的將不勝感激!

感謝

+2

爲什麼'ASCIIEncoding'? PHP很可能使用UTF-8進行輸入,所以也使用'UTF8Encoding'。雖然這對於「測試」密碼不應該有影響... – Jon

+0

1.檢查現有應用程序是否使用salt。它可能會(雖然,鑑於該應用程序使用密碼哈希MD5,我不能打賭) - 請參閱[你想知道的關於建立一個安全的密碼重置功能](http://www.troyhunt.com/ 2012/05/everything-you-ever-wanted-to-know.html)以獲得更多關於密碼存儲的信息; 2.密碼字符集是否僅限於(ASCII的子集)? –

+0

此外,「數據庫中的內容」是無關緊要的。 PHP代碼可能每次都在數據庫中寫入隨機字節,您是否可以通過查看結果來匹配它的行爲?你需要看代碼。 – Jon

回答

1

下面應該給你相同的十六進制字符串作爲PHP的md5:

public string GetMd5Hex(MD5 crypt, string input) 
{ 
    return crypt.ComputeHash(UTF8Encoding.UTF8.GetBytes(input)) 
     .Select<byte, string>(a => a.ToString("x2")) 
     .Aggregate<string>((a, b) => string.Format("{0}{1}", a, b)); 
}