程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 關於數據庫密碼散列加密(hash)

關於數據庫密碼散列加密(hash)

編輯:.NET實例教程

1、添加一組數據; 

private void btnAdd_Click(object sender, System.EventArgs e)
  {
   if ((txtNameAdd.Text != "") && (txtPwdAdd.Text!=""))
   {
    //new a dbconnection,數據庫為db目錄下的userdb.mdb
    string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
     + Server.MapPath(@".\db\userdb.mdb")
     + ";Mode=Share Deny None;Persist Security Info=False";
    OleDbConnection conn = new OleDbConnection(connstr);
    conn.Open ();
    //檢查是否用戶名存在
    string sql = "SELECT * FROM [userinfo] WHERE [user_name]='" + txtNameAdd.Text + "'" ;
    OleDbCommand cmd = new OleDbCommand(sql,conn);
    OleDbDataReader dr = cmd.ExecuteReader();
     if (dr.Read() == true)
    {
     MsgBox("用戶名存在!");
     return;
    }
    dr.Close ();
    
    //使用MD5 Hash算法進行散列加密
    MD5CryptoServiceProvider HashMD5 = new MD5CryptoServiceProvider();
    string newPwd = ASCIIEncoding.ASCII.GetString (HashMD5.ComputeHash( ASCIIEncoding.ASCII.GetBytes(txtPwdAdd.Text )));
    //將加密後的passWord添加如數據庫中
    sql = "INSERT INTO [userinfo]([user_name],[user_pwd])"
     + "VALUES('" + txtNameAdd.Text + "','" + newPwd + "')";
    cmd.CommandText = sql;
    cmd.ExecuteNonQuery ();
    conn.Close();
    MsgBox("成功添加用戶:" + txtNameAdd.Text + " 密碼:" + txtPwdAdd.Text );
   }
  }

2、驗證數據

private void btnCheck_Click(object sender,

System.EventArgs e)
  {
   if ((txtNameCheck.Text != "") && (txtPwdCheck.Text!=""))
   {
    //new a dbconnection,數據庫為db目錄下的userdb.mdb
    string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
     + Server.MapPath(@".\db\userdb.mdb")
     + ";Mode=Share Deny None;Persist Security Info=False";
    OleDbConnection conn = new OleDbConnection(connstr);
    conn.Open ();
    //根據用戶名,讀出密碼
    string sql = "SELECT [user_pwd] FROM [userinfo] WHERE [user_name]='" + txtNameCheck.Text + "'";
    OleDbCommand cmd = new OleDbCommand(sql,conn);
    OleDbDataReader dr = cmd.ExecuteReader();
    if (dr.Read() == true)
    {
     //將輸入密碼進行散列加密,與讀出密碼進行比較
     MD5CryptoServiceProvider HashMD5 = new MD5CryptoServiceProvider();
     string newPwd = ASCIIEncoding.ASCII.GetString (HashMD5.ComputeHash( ASCIIEncoding.ASCII.GetBytes(txtPwdCheck.Text )));
     if (dr.GetValue(0).ToString() == newPwd)
     {
      MsgBox("通過驗證!");
     }
     else
     {
      MsgBox("用戶信息錯誤!");
     }
    }
    dr.Close ();
   }
  
  }

3、彈出信息

private void MsgBox(string msg)
  {
   Response.Write ("<script language='JavaScript'>window.alert('" + msg + "');</script>");
  }


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved