0

I've got my passwords to be hashed in my ASP.NET Webforms.

How do I then enter the hashed password into the database via a string?

SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);

dbCon.Open();

SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (@firstName, @surname, @email, @username, @passwordHash)", dbCon);

cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);

string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.ToString("passwordHash");

cmd.ExecuteNonQuery();

I knew I couldn't use .AddWithValue and thought of .ToString may have been the one to use.

I am new to C#.

Thanks.

5
  • 2
    "I knew I couldn't use .AddWithValue " Why did you think that? Commented Jun 1, 2017 at 14:38
  • 5
    As a side note, you should be wrapping your SqlConnection and SqlCommand statements in using blocks. Commented Jun 1, 2017 at 14:39
  • if you just hash your password to a string and want to store that string, you can indeed just use AddWithValue. What you're doing up there cmd.Parameters.ToString("passwordHash") will not accomplish much, because the ToString() method just returns a (formatted) string and doesn't do any assignment internally, besides it will try to take "passwordHash" as the format string wich doesn't make much sense. Commented Jun 1, 2017 at 14:41
  • What is the problem with cmd.Parameters.AddWithValue("passwordHash", passwordHash);? Commented Jun 1, 2017 at 14:45
  • 1
    @AmitJoshi blogs.msmvps.com/jcoehoorn/blog/2014/05/12/… Commented Jun 1, 2017 at 15:16

1 Answer 1

3

Does this work?

   SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
{
    dbCon.Open();
    SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (@firstName,@surname,@email,@username,@passwordHash)", dbCon);
    cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
    cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
    cmd.Parameters.AddWithValue("email", emailTxt.Text);
    cmd.Parameters.AddWithValue("username", usernameTxt.Text);
    string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
    cmd.Parameters.AddWithValue("passwordHash", passwordHash);


    cmd.ExecuteNonQuery();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @mjwills! Works fine, never thought of trying that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.