2013-06-27 115 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)); 
}