取得 MD5 (SHA1) 的三種方法

取得 MD5 (SHA1) 的三種方法

取的字串的 MD5(SHA1) 數值的三種方法:

1. 使用 System.Web.Security 命名空間
FormsAuthentication.HashPasswordForStoringInConfigFile 方法

2. 使用 System.Security.Cryptography 命名空間
MD5CryptoServiceProvider 類別、 SHA1CryptoServiceProvider 類別

3. 使用 SQL Server 2005 的內建函數
hashbytes

取得 MD5 範例的程式碼:

   1:  private void button1_Click(object sender, EventArgs e)
   2:  {
   3:      string source = "Test String";
   4:   
   5:      // Method 1: FormsAuthentication.HashPasswordForStoringInConfigFile
   6:      string m1 = FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
   7:      string m2 = GetMD5(source);
   8:      string m3 = MD5Sql(source);
   9:   
  10:      MessageBox.Show(string.Format("source: {0}, m1:{1}, m22:{2}, m3:{3}", source, m1, m2, m3));
  11:  }
  12:   
  13:  // Method 2: MD5CryptoServiceProvider
  14:  private string GetMD5(string source)
  15:  {
  16:      MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  17:      byte[] bytValue = Encoding.UTF8.GetBytes(source);
  18:      byte[] bytHash = md5.ComputeHash(bytValue);
  19:      md5.Clear();
  20:   
  21:      StringBuilder sb = new StringBuilder();
  22:      for (int i = 0; i < bytHash.Length; i++)
  23:      {
  24:          sb.Append(bytHash[i].ToString("X").PadLeft(2, '0'));
  25:      }
  26:   
  27:      return sb.ToString().ToLower();
  28:  }
  29:   
  30:  // Method 3: SQL Server 2005 MD5
  31:  public string MD5Sql(string source)
  32:  {
  33:      string strConn = @"Connectionstring";
  34:      SqlConnection conn = new SqlConnection(strConn);
  35:      SqlCommand cmd = new SqlCommand("select master.sys.fn_VarBinToHexStr(hashbytes('MD5', @sDataIn))", conn);
  36:      cmd.Parameters.Add("@sDataIn", SqlDbType.VarChar);
  37:      cmd.Parameters["@sDataIn"].Value = source;
  38:   
  39:      conn.Open();
  40:      string s = cmd.ExecuteScalar().ToString().Substring(2).ToLower();
  41:      conn.Close();
  42:   
  43:      return s;
  44:  }