首先,我假设了这一点以及之前的一些问题,我观察到,实际上“比较散列值”与通过数据库提交的散列值的最简单方法是看查询是否,“'SELECT','WHERE','FROM'(x = x2)“语句实际上已成功执行(返回大于零的值)。
private void button1_Click(object sender, EventArgs e)
{
string AppUsername = textBox2.Text.ToString();
string AppPassword = textBox1.Text.ToString();
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
var pbkdf2 = new Rfc2898DeriveBytes(AppPassword, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
string savedPasswordHash = Convert.ToBase64String(hashBytes); // <-- see ' https://stackoverflow.com/questions/4181198/how-to-hash-a-password ' for the part on comparing the recalculated
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open(); //dbo.data?
var cmd = new SqlCommand(@"SELECT Username, Hash FROM data WHERE (Hash = @savedPasswordHash");
cmd.Parameters.AddWithValue("@savedPasswordHash", savedPasswordHash);//^ this should work right?
if (cmd.ExecuteNonQuery() > 0) {
MessageBox.Show(" Query successful..something matched.. ");
}
}
我已经确认本地数据库中填充的哈希值应与被比较的哈希值匹配。
但是我相信第二段代码有问题:
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open(); //dbo.data?
var cmd = new SqlCommand(@"SELECT Username, Hash FROM data WHERE (Hash = @savedPasswordHash");
cmd.Parameters.AddWithValue("@savedPasswordHash", savedPasswordHash);//^ this should work right?
if (cmd.ExecuteNonQuery() > 0) {
MessageBox.Show(" Query successful..something matched.. ");
如果将其归类为重复问题,我不会不同意选民。但是从我先前的问题中确定的结果来看,没有什么能真正帮助我解决问题。
我刚刚意识到我得到的实际错误与实际连接有关:
ExecuteNonQuery:连接属性尚未初始化。
我使用与输入值相同的代码。
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
我仍然认为问题必须出在实际的查询设置或参数上,但我不确定:/
我发现初始化错误出了什么问题。就像它说的那样,我从未真正初始化过连接。
添加以下代码:
cmd.Connection = con;
修复了该问题。
代码现在如下:
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open(); //dbo.data?
var cmd = new SqlCommand(@"SELECT Username, Hash FROM data WHERE (Hash = @savedPasswordHash");
cmd.Connection = con;
cmd.Parameters.AddWithValue("@savedPasswordHash", savedPasswordHash);//^ this should work right?
if (cmd.ExecuteNonQuery() > 0) {
MessageBox.Show(" Query successful..something matched.. ");
//change page.. load a profile?
}
但是返回的错误与我的查询的实际语法有关,最初我认为与该错误有关。
这是不正确的语法在'@savedPasswordHash'附近
任何SQL语法建议都将受到欢迎。