基於.net的加密匯總(2)C#密碼加密

來源:互聯網
上載者:User

引用C#密碼加密

EncryptPassWord類:

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Security.Cryptography; using System.Text;
publicclass EncryptPassWord {     ///<summary>     /// 擷取密鑰     ///</summary>     ///<returns></returns>    publicstaticstring CreateSalt()     {         byte[] data =newbyte[8];         new RNGCryptoServiceProvider().GetBytes(data);         return Convert.ToBase64String(data);     }
    ///<summary>     /// 加密密碼     ///</summary>     ///<param name="pwdString"></param>     ///<param name="salt"></param>     ///<returns></returns>    publicstaticstring EncryptPwd(string pwdString, string salt)     {         if (salt ==null|| salt =="")         {             return pwdString;         }         byte[] bytes = Encoding.Unicode.GetBytes(salt.ToLower().Trim() + pwdString.Trim());         return BitConverter.ToString(((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(bytes));     } }

 

 

DESEncrypt類:

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Security.Cryptography; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Text; ///<summary>/// Summary description for DESEncrypt ///</summary>publicclass DESEncrypt {     privatestring iv ="12345678";     privatestring key ="12345678";     private Encoding encoding =new UnicodeEncoding();     private DES des;
    public DESEncrypt()     {         des =new DESCryptoServiceProvider();     }
    ///<summary>     /// 設定加密金鑰     ///</summary>    publicstring EncryptKey     {         get { returnthis.key; }         set         {             this.key = value;         }            }
    ///<summary>     /// 要加密字元的編碼模式     ///</summary>    public Encoding EncodingMode     {         get { returnthis.encoding; }         set { this.encoding = value; }     }
    ///<summary>     /// 加密字串並返回加密後的結果     ///</summary>     ///<param name="str"></param>     ///<returns></returns>    publicstring EncryptString(string str)     {         byte[] ivb = Encoding.ASCII.GetBytes(this.iv);         byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);//得到加密金鑰        byte[] toEncrypt =this.EncodingMode.GetBytes(str);//得到要加密的內容        byte[] encrypted;         ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);         MemoryStream msEncrypt =new MemoryStream();         CryptoStream csEncrypt =new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);         csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);         csEncrypt.FlushFinalBlock();         encrypted = msEncrypt.ToArray();         csEncrypt.Close();         msEncrypt.Close();         returnthis.EncodingMode.GetString(encrypted);     } }

 

1.原理:每次產生一個隨機字串作為密匙,使用者輸入一個密碼,密碼經過密匙加密得到一個字串存放在資料庫中...當需要驗證密碼時,要先得到密匙才能驗證.

  (1).登入時,驗證代碼

 

//根據使用者名稱得到使用者資訊       DataTable dt = WYTWeb.UserDAO.UserLogin(userName); if (dt.Rows.Count ==0) {     return-2;//使用者不存在 }
DataRow row = dt.Rows[0]; //得到密匙string salt = row["salt"].ToString(); //驗證密碼是否正確if (EncryptPassWord.EncryptPwd(password, salt) == row["password"].ToString()) {       //登入成功 }

 

(2)修改密碼時(與插入一條新密碼一樣)

 

//從基類獲得登入idint userId = LoginUser_Id; //獲得密匙string salt = EncryptPassWord.CreateSalt(); //得到經過加密後的"密碼"string password = EncryptPassWord.EncryptPwd(txtPassword.Text.Trim(), salt); //修改原資料int result = WYTWeb.UserDAO.EditPassword(userId, password, salt); if (result >0) {      WYTWeb.LogDAO.InsertLog("info","wytWeb","使用者"+userId+"修改了密碼", userId ,this.Request.UserHostAddress.ToString());      ShowMessage("密碼修改成功");            //this.Response.Redirect("CompanyInfo.aspx"); } else {     WYTWeb.LogDAO.InsertLog("info", "wytWeb", "使用者"+ userId +"修改密碼失敗", userId, this.Request.UserHostAddress.ToString());     ShowMessage("密碼修改失敗"); }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.