2012-05-18 201 views
1

我想实现哈希和盐渍的密码登录形式,其中我有简单的MySQL连接的数据库包含id-Int,用户名VarChar,密码-VarChar和盐-VarChar。当我尝试调试程序并输入正确的数据,我仍然得到试图实现哈希和盐渍的密码登录形式

错误的细节

显示框。无论如何,看看代码如何,你知道我的错误在哪里以及如何解决这个问题。 PS:请注意,对于我的数据库中的“salt”字段,我尝试插入与密码相同的数据,尝试将它放在空白处,尝试将其从varchar更改为Sha1,但仍得到相同的错误。

static byte[] GenerateSaltedHash(string plainText, string salt) 
    { 
     HashAlgorithm algorithm = new SHA256Managed(); 

     byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(plainText); 
     byte[] saltBytes = Convert.FromBase64String(salt); 

     byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; 
     saltBytes.CopyTo(plainTextWithSaltBytes, 0); 
     plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length); 

     byte[] hash = algorithm.ComputeHash(plainTextWithSaltBytes); 

     return hash; 
    } 

     public bool tryLogin(string username , string password) 
     { 
      using (var con = new MySqlConnection("host=localhost;user=admin;password=password;database=sozopouk_test2;")) 
      { 
       con.Open(); 

       var salt = string.Empty; 

       using (MySqlCommand cmd = new MySqlCommand("Select salt From niki where user_name = @username", con)) 
       { 
        cmd.Parameters.AddWithValue("@username", username); 

        salt = cmd.ExecuteScalar() as string; 
       } 

       if (string.IsNullOrEmpty(salt)) return false; 

       var hashedPassword = GenerateSaltedHash(password, salt); 

       using (var cmd = new MySqlCommand("Select * FROM niki WHERE user_name = @username and user_password = @password", con)) 
       { 
        cmd.Parameters.AddWithValue("@username", username); 
        cmd.Parameters.AddWithValue("@password", hashedPassword); 

        using (var reader = cmd.ExecuteReader()) 
        { 
         return reader.Read(); 
        } 
       } 
      } 
      } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      if (tryLogin(user.Text, pass.Text) == true) 
      { 
       MainScreen F2 = new MainScreen(); 
       F2.Show(); 
       this.Hide(); 
      } 

      else MessageBox.Show("Wrong details!"); 
     } 
+0

您的'niki'表中的'salt'列是否包含您尝试登录的用户名的值? – Bridge

+0

@Bridge当前salt列是空的,并且被定义为varchar 255 –

+0

那么这就是返回false的原因。你的登录方法有这样的代码:'if(string.IsNullOrEmpty(salt))return false;' – Bridge

回答

0

我试图重现您的问题。 (就在哈希算法) 看来,这条线是不正确的

plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length); 

相反,你应该使用

plainTextBytes.CopyTo(plainTextWithSaltBytes, saltBytes.Length); 

但是这给了我一个异常不reader.Read假。
所以有可能这个问题是不同的。 您应该尝试在调试之前在阅读器之前停止该程序。 阅读并检查@username和@password的值。
使用该信息,使用您的首选MySql管理器,检查用户表是否包含参数中的值。

+0

取代您生成的代码,但仍然** **错误**任何想法? PS:我应该将salt字段留空并定义为varchar吗? –

+0

您是否重新生成算法更改的用户密码?如果存在散列密码的用户,您是否检查过调试?这里有一个示例,详细解释如何[生成](http://msdn.microsoft.com/en-us/library/aa545602(v = CS.70).aspx)Hashpassword – Steve