2013-06-05 40 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