Jotin

生命在于运动

 

c#兼容 PHP中的md5

由于工作需要,需要使用C#去对一个php程序做二次开发.在登录验证的时候,发现一个小问题.

就是用C#写的md5算法得出的结果和php的md5()得出的结果有时候会不一样. 导致有些账号的密码验证不能通过.后来网上找了一下,在国外一个网站上找到了答案.

 

C#常用的MD5算法.

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) {
            ret += a.ToString ("x");
      }
      return ret ;
   }
   catch {
      throw;
   } 

} 

 

但是此算法与md5()得出的结果是不一样的.后调整为如下,即可以了.

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;
   } 

} 

 

 

 

posted on 2010-06-12 16:01  Jotin  阅读(3144)  评论(2编辑  收藏  举报

导航