[ASP.NET][C#]密碼加密

  • 8044
  • 0

摘要:[ASP.NET],[C#]密碼加密

密碼加密是防止資料庫被破解而讓所有使用者密碼外洩造成資安問題

以下是簡單的密碼加密方法(寫給自己看XD)

首先需加入服務參考:

System.Web

版本為2.0若找不到參考請用版本排序找尋2.0的版本=.=

加密後寫入資料庫

必須引用using System.Web

片段程式碼:


//使用FormsAuthentication.HashPasswordForStoringInConfigFile方法,
//第一個參數是要加密的字串,第二個參數是加密的演算法
string Encryption = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPass.Text, System.Web.Configuration.FormsAuthPasswordFormat.SHA1.ToString());
strCmd = "INSERT INTO 使用者" +
                 " (使用者, 密碼) VALUES" +
                 "('" + txtUser.Text + "','" + Encryption + "')";

驗證資料庫內是否正確

片段程式碼:


//使用FormsAuthentication.HashPasswordForStoringInConfigFile方法,
//第一個參數是要加密的字串,第二個參數是加密的演算法
string Encryption = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPass.Text, System.Web.Configuration.FormsAuthPasswordFormat.SHA1.ToString());
string strCmd = "SELECT 使用者, 密碼" +
                " FROM   使用者 WHERE" +
                "(使用者 = '" + txtUser.Text + "') AND (密碼 = '" + Encryption + "')";

簡單來講就是把加密後的密碼寫入資料庫

若要驗證時先將使用者密碼透過加密的方式再與資料庫內比對若相同則驗證通過

以上只是簡單的加密方法:D

我只是個小小的入門者