Reputation: 1351
I have a database associated with my winforms program. It stores name, usertype, hash and salt. Ive sorted the registration and writing details, but i dont know how to save the salt (when read from database) as a variable. Here is my code:
public string getSalt()
{
SqlConnection connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes");
connection.Open();
string selection = "select DISTINCT Salt from Logins where Name = '"+userNameBox.Text+"'";
SqlCommand command = new SqlCommand(selection, connection);
if (command.ExecuteScalar() != null)
{
connection.Close();
return selection;
}
else
{
connection.Close();
return "Error";
}
}
As you can see, its returning selection, which is "select DISTINCT Salt from Logins where Name = '"+userNameBox.Text+"'". How do i save the salt as the variable to return?
Upvotes: 1
Views: 238
Reputation: 416121
This should do it, and also fixes the gaping sql injection vulnerability in the original:
public string getSalt()
{
string sql = "select DISTINCT Salt from Logins where Name = @username";
using (var connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes"))
using (var command = new SqlCommand(sql, connection))
{
//guessing at the column length here. Use actual column size instead of 20
command.Parameters.Add("@username", SqlDbType.NVarChar, 20).Value = userNameBox.Text;
connection.Open();
return (command.ExecuteScalar() as string) ?? "Error";
}
}
Upvotes: 3