使用ExecuteNonQuery()更新表-引发异常

时间:2019-06-17 02:01:26

标签: c# .net sql-server

我正在尝试创建一个简单的应用程序,该应用程序允许用户“注册”并存储用户名和密码。密码先经过加密和哈希处理,然后存储到SQL Server数据库中。我在更新表格时遇到了问题。我将本文用作参考(https://medium.com/@mehanix/lets-talk-security-salted-password-hashing-in-c-5460be5c3aae

我已经调试了每一行,看来我遇到的问题在ExceptionNonQuery()上。我已验证到数据库的连接已打开。我处理不正确吗?

private void Button2_Click(object sender, EventArgs e)
{
    // hashing, create new byte array
    byte[] salt;

    //generate salt, this method is a random number generator. Will be storing hash and salt into database. 
    new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);

    //Hashing algorithm we're using is PBKDF2 (Password-Based Key Derivation Function 2).
    var pbkdf2 = new Rfc2898DeriveBytes(Password.Text, salt, 10000);

    //Storing...
    byte[] hash = pbkdf2.GetBytes(20);

    //20 bytes are hash, 16 is salt. equals to 36 bits
    byte[] hashBytes = new byte[36];

    Array.Copy(salt, 0, hashBytes, 0, 16);
    Array.Copy(hash, 0, hashBytes, 16, 20);

    //convert byte array to string
    string savedPasswordHash = Convert.ToBase64String(hashBytes);

    Debug.WriteLine(hashBytes);

    try
    {
        Debug.WriteLine("Testing Database connection");

        string constring = @"my local sql server.......";
        string commString = "INSERT INTO [Users](UserName, Password) Values (@val1, @val2)";

        //connect to db
        using (SqlConnection conn = new SqlConnection(constring))
        {
            using (SqlCommand comm = new SqlCommand(commString, conn))
            {
                comm.Connection = conn;
                Debug.WriteLine("Connecting to database");
                comm.CommandText = commString;

                Debug.WriteLine("Adding variables to DB table Users");
                comm.Parameters.AddWithValue("@val1", UserName.Text);
                Debug.WriteLine("Added username...");
                comm.Parameters.AddWithValue("@val1", savedPasswordHash);
                Debug.WriteLine("Added Password...");
                Debug.WriteLine(UserName.Text);
                Debug.WriteLine(savedPasswordHash);

                Debug.WriteLine("Connecing to SQL...");
                conn.Open();
                Debug.WriteLine("Connection successful..");

                Debug.WriteLine("Running query..");
                //comm.Connection.Open();
                comm.ExecuteNonQuery();

                Debug.WriteLine("qUERY SENT SUCCESS");
                conn.Close();
            }
        }

        MessageBox.Show("Successfully registered!");
    }
    catch
    {
        Debug.WriteLine(hashBytes);
        MessageBox.Show("A registration error has occured.");
    }
}

在输出中,我看到了

  

引发的异常:System.Data.dll中的“ System.Data.SqlClient.SqlException”。

理想情况下,我的主要目标是将这些数据填充到表中。一旦发现问题,我应该可以对此进行验证。

0 个答案:

没有答案