C# 實現MD5加密

來源:互聯網
上載者:User

標籤:

C#實現MD5加密

 

摘自:http://blog.csdn.net/shenghui188/archive/2010/03/28/5423959.aspx

 

方法一:

首先,先簡單介紹一下MD5

MD5的全稱是message-digest algorithm 5(資訊-摘要演算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest開發出來, 經md2、md3和md4發展而來。

MD5具有很好的安全性(因為它具有無法復原的特徵,加過密的密文經過解密後和加密前的東東相同的可能性極小)

引用
using System.Security.Cryptography;
using System.Text;

具體代碼如下(寫在按鈕的Click事件裡):
byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim());    //tbPass為輸入密碼的文字框
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-","");  //tbMd5pass為輸出加密文本的文字框

 

 

方法二:

C# md5加密(上)
string a; //加密前資料
string b; //加密後資料
b=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")

using   System;
using   System.Security.Cryptography;

方法2

public   static   string   GetMD5(string   myString)   
{
MD5   md5     =   new   MD5CryptoServiceProvider();
byte[]   fromData   =   System.Text.Encoding.Unicode.GetBytes(myString);
byte[]   targetData   =   md5.ComputeHash(fromData);
string   byte2String   =   null;

for   (int   i=0;   i<targetData.Length;   i++)   
{
byte2String   +=   targetData[i].ToString("x");
}

return   byte2String;
}

using   System.Security.Cryptography;


///   <summary>
///   給一個字串進行MD5加密
///   </summary>
///   <param   name="strText">待加密字串</param>
///   <returns>加密後的字串</returns>
public   static   string   MD5Encrypt(string   strText)
{   
MD5   md5   =   new   MD5CryptoServiceProvider();
byte[]   result   =   md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return   System.Text.Encoding.Default.GetString(result);
}


C# MD5加密 
using System.Security.Cryptography;


private void btnOK_Click(object sender, System.EventArgs e)
{
   string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";
   if(texName.Text.Trim()=="")
   {
    this.RegisterStartupScript("sf","<script language=‘javascript‘>alert(‘使用者名稱不可為空‘);document.all(‘texName‘).focus()</script>");
    return;
   }
   else if(texPassword.Text.Trim()=="")
   {
    this.RegisterStartupScript("sfs","<script language=‘javascript‘>alert(‘密碼不可為空‘);document.all(‘texPassword‘).focus()</script>");
    return;
   }
   else
   {
    //將擷取的密碼加密與資料庫中加了密的密碼相比較
    byte[] by = md5.ComputeHash(utf.GetBytes(texPassword.Text.Trim()));
    string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);
    conn.ConnectionString=strConn;
    SqlCommand comm = new SqlCommand();
    string name = texName.Text.Trim().ToString();
    comm.CommandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";
    comm.Parameters.Add("@name",SqlDbType.NVarChar,40);
    comm.Parameters["@name"].Value=name;
    try
    {     
     conn.Open();
     comm.Connection=conn;
     SqlDataReader dr=comm.ExecuteReader();
     if(dr.Read())
     {
      //使用者存在,對密碼進行檢查
      if(dr.GetValue(0).Equals(resultPass))
      {
       string user_name=dr.GetValue(1).ToString();
       string user_Accountno=texName.Text.Trim();
       Session["logon_name"]=user_name;
       Session["logon_Accountno"]=user_Accountno;
       //登入成功,進行頁面導向

      }
      else
      {
       this.RegisterStartupScript("wp","<script language=‘javascript‘>alert(‘密碼錯誤,請檢查。‘)</script>");
      }
      
     }
     else
     {
      this.RegisterStartupScript("nu","<script language=javascript>alert(‘使用者名稱不存在,請檢查。‘)</script>");
     }
    }
    catch(Exception exec)
    { 
     this.RegisterStartupScript("wc","<script language=javascript>alert(‘網路連接有異,請稍後重試。‘)</script>");
    } 
    finally
    {
     conn.Close();
    }
   }
}

 

 方法三
C# MD5加密

C#開發筆記   一、C# MD5-16位加密執行個體,32位加密執行個體(兩種方法)

環境:vs.net2005/sql server2000/xp測試通過
1.MD5 16位加密執行個體
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace md5
{
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine(UserMd5("8"));
             Console.WriteLine(GetMd5Str("8"));
         }
        /**//// <summary>
        /// MD5 16位加密 加密後密碼為大寫
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString)
        {
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
             t2 = t2.Replace("-", "");
            return t2;
         }

  /**//// <summary>
        /// MD5 16位加密 加密後密碼為小寫
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString)
        {
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
             t2 = t2.Replace("-", "");

            t2 = t2.ToLower();

             return t2;
         }


        /**//// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
       static  string UserMd5(string str)
        {
            string cl = str;
            string pwd = "";
             MD5 md5 = MD5.Create();//執行個體化一個md5對像
            // 加密後是一個位元組類型的數組,這裡要注意編碼UTF8/Unicode等的選擇 
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通過使用迴圈,將位元組類型的數群組轉換為字串,此字串是常規字元格式設定化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 將得到的字串使用十六進位類型格式。格式後的字元是小寫字母,如果使用大寫(X)則格式後的字元是大寫字元

                 pwd = pwd + s[i].ToString("X");
                
             }
            return pwd;
         }
     }
}

using System.Security.Cryptography;
using System.Text;

public static string StringToMD5Hash(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }


 

二、首先在介面中引入:using System.Web.Security;

假設密碼對話方塊名字password,對輸入的密碼加密後存入變數pwd中,語句如下:

 string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text, "MD5");

如果要錄入則錄入pwd,這樣資料庫實際的密碼為202*****等亂碼了。

如果登入查詢則要:

select username,password from users where username=‘"+ UserName.Text +"‘ and password=‘"+ pwd +"‘

因為MD5不能解密,只能把原始密碼加密後與資料庫中加密的密碼比較

三、C# MD5 加密方法 16位或32位

  public string md5(string str,int code) 
  { 
    if(code==16) //16位MD5加密(取32位加密的9~25字元) 
   { 
       return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ; 
   }  
   else//32位加密 
   { 
       return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower(); 
   }  
 }

    四、做一個網站時,必然涉及使用者登入,使用者登入必然涉及密碼,密碼必然涉及安全,安全必然涉及加密。
加密現時最流行也是據說最安全的演算法是MD5演算法,MD5是一種無法復原的演算法,也就是 明文經過加密後,根據加密過的密文無法還原出明文來。
目前有好多網站專搞MD5破密,百度上搜一下MD5就搜出一大堆了,今天早上無聊試了幾個破密網站,6位以內純數字密碼的MD5密文可以還原出明文,長點的或帶字元的就不行了。他們是採用窮舉對比的,就是說把收錄到的明文和密文放到資料庫裡,通過密文的對比來確定明文,畢竟收錄的資料有限,所以破解的密碼很有限。
扯遠了,搞破密MD5需要大量的MONEY,因為要一個運算得超快的電腦和一個尋找效能超好的資料庫和超大的資料庫收錄。但搞加密就比較簡單。以下是我用C#寫的一個MD5加密的方法,用到.NET中的方法, 通過MD5_APP.StringToMD5(string str, int i)可以直接調用:

public class MD5_APP
{
 public MD5_APP()
 {
     
 }

    public static string StringToMD5(string str, int i)
    {
        //擷取要加密的欄位,並轉化為Byte[]數組
        byte[] data = System.Text.Encoding.Unicode.GetBytes(str.ToCharArray());
        //建立Data Encryption Service
        System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        //加密Byte[]數組
        byte[] result = md5.ComputeHash(data);
        //將加密後的數組轉化為欄位
        if (i == 16 && str != string.Empty)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
        }
        else if (i == 32 && str != string.Empty)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
        }
        else
        {
            switch (i)
            {
                case 16: return "000000000000000";
                case 32: return "000000000000000000000000000000";
                default: return "請確保調用函數時第二個參數為16或32";
            }

        }
    }

 

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shenghui188/archive/2010/03/28/5423959.aspx

C# 實現MD5加密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.