2013-06-05 39 views
0

我正在爲學校做一個應用程序,並且在將密碼插入到我的用戶數據庫時需要密碼幫助。我是用c#編程語言編程的,我正在使用MS服務器2008 R2用於操縱我的數據庫。我正在考慮做一個HASH加密,如果有人幫助我,我會愛上它。當插入數據庫時​​哈希加密密碼

這是我將數據插入到數據庫代碼:

using (SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True")) //MLHIDE 
     using (SqlCommand sc = new SqlCommand("if NOT exists (select * from users where UserName = @username) insert into users (userName, password) values(@userName, @password)", con)) 
     { 
      con.Open(); 
      sc.Parameters.AddWithValue("@username", korisnik.Text); 
      sc.Parameters.AddWithValue("@password", pass.Text); 
      int o = sc.ExecuteNonQuery(); 
      if (o == -1) 
      { 
       MessageBox.Show(Ulaz.Properties.Resources.Niste_ubačeni_u_bazi_korisničk); 
       this.Hide(); 
       new Registracija().Show(); 
      } 
      else 
      { 
       MessageBox.Show(Ulaz.Properties.Resources.Ubačeni_ste_u_bazi); 
       con.Close(); 
       this.Hide(); 
       new Form1().Show(); 

      } 

,這裏是我的登錄校驗碼:

SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True"); 
     SqlCommand cmd = new SqlCommand("select * from users where userName='" + user.Text + "' and password='" + pass.Text + "'", con); //MLHIDE 
     con.Open(); 
     SqlDataReader re = cmd.ExecuteReader(); 

     if (re.Read()) 
     { 
      ImeUsera = user.Text; 
      new UserMode().Show(); 
      this.Hide(); 
     } 
      else 
      { 
       this.Hide(); 
       new LoginFail().Show(); 
      } 
     } 

我使用了一些多語言插件,所以他轉變我的琴絃成''Ulaz.Properties.Resources。''和類似。

+0

散列和加密不是同一件事 – emd

+0

散列(在您的上下文中) - >單向 http://en.wikipedia.org/wiki/ Cryptographic_hash_function 加密 - >雙向(對稱或公鑰) http://en.wikipedia.org/wiki/Encryption – Zerkz

+0

好的,對於我錯誤地使用術語感到抱歉。 – user2445530

回答

1

哈希文本字符串,你可以使用這樣的函數

private string GetHashedText(string inputData) 
{ 
    byte[] tmpSource; 
    byte[] tmpData; 
    tmpSource = ASCIIEncoding.ASCII.GetBytes(inputData); 
    tmpData = new MD5CryptoServiceProvider().ComputeHash(tmpSource); 
    return Convert.ToBase64String(tmpData); 
} 

,並適用於你的用戶輸入。然後將結果存儲在數據庫中。在登錄時,您將散列函數重新應用於輸入的密碼,並根據存儲的值檢查結果。

所以你插入的代碼編寫

sc.Parameters.AddWithValue("@password", GetHashedText(pass.Text)); 

,並在您檢查

.... 
SqlCommand cmd = new SqlCommand("select * from users where [email protected] and [email protected]", con); 
con.Open(); 
cmd.Parameters.AddWithValue("@user",user.Text); 
cmd.Parameters.AddWithValue("@pass", GetHashedText(pass.Text)); 
SqlDataReader re = cmd.ExecuteReader(); 
if (re.Read()) 
..... 

記住,散列是不可逆的,所以你不能檢索散列文本原始密碼。將Hash函數應用於文本並將其存儲爲base64字符串。如果您的用戶忘記密碼,則需要將其重置爲已知值。沒有辦法告訴他原來的密碼。

順便說一句,爲什麼在你的檢查中,你不像使用插入代碼那樣使用參數?切勿使用字符串連接來構建SQL查詢。即使您急於完成作業

+0

我的意思是改變這一點。我現在陷入其他一些東西,但我一定會更改登錄檢查。謝謝史蒂夫的回答! – user2445530