The password in the database still stored as a text - c#

I want to store a password in the database, but when I click Submit button, it added successfully to the database, but it does not stored the password in the database as random text, but as the original text. How could I fix this?
Here is the code that I am using:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
string myPassword;
string strHashedPassword;
string strStoredPassword;
int mySalt;
bool checking = false;
public Registration()
{
InitializeComponent();
}
private void Registration_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
Checking _checking = new Checking();
_checking.ShowDialog();
checking = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "" || this.textBox2.Text == "" || this.textBox3.Text == "" || this.textBox4.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
AddDatabase(sender, e);
}
}
private void AddDatabase(object sender, EventArgs e)
{
if (checking.Equals(false))
{
MessageBox.Show("You have to check first", "Warning", MessageBoxButtons.OK);
}
else
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType], [UserStore]) VALUES (#Username, #Password, #UserType, #UserStore)";
OleDbConnection _conn = new OleDbConnection(connectionString);
_conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, _conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.textBox3.Text;
cmd.Parameters.Add("#UserStore", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserStore"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
DialogResult _dialogResult = MessageBox.Show("Added Successfully", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
CreateRandomPassword();
this.Close();
}
}
}
}
private void CreateRandomPassword()
{
// Generate a new random password string
myPassword = this.textBox2.Text;
// Generate a new random salt
mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(myPassword, mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the database
strHashedPassword = pwd.ComputeSaltedHash();
strStoredPassword = strHashedPassword;
}
Thank you!
Your answer much appreciated!

You're using this.textBox2.Text for the #Password portion of the query, but your CreateRandomPassword() method only changes strStoredPassword and strHashedPassword (As an aside, I don't really see why you have 2 variables to hold the same value, it's redundant).
You should change
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
to
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;
and move the call to CreateRandomPassword() up above the query execute.

In your "AddDatabase" function, change textbox value to "strStoredPassword"
like below
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;

Related

C# UWP Login form checking credentials in MySQL remote database

I got stuck after couple of hours of research. I'm trying to make a basic Universal Windows App with login form - after clicking a button, credentials in textboxes are checked with remote MySQL database. If valid, app shoud navigate to another specified page. If not, error message is displayed.
I can't find error in my code below. After clicking the button Windows' blue circle spins and after couple of seconds returns to VS2017. No errors and warnings. State.ToString() returns 'Open' so I do have a connection with DB. What I'm doing wrong?
public sealed partial class MainPage : Page
{
const string connString = "server=my_server;pwd=pass;uid=user_id;database=mydb;persistsecurityinfo=True";
MySqlConnection conn = new MySqlConnection(connString);
public MainPage()
{
this.InitializeComponent();
}
private void DbConnection()
{
try
{
conn.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool DataValidation(string user, string pass)
{
DbConnection();
MySqlCommand cmd = new MySqlCommand("SELECT Username, Password FROM Users WHERE Username=#user AND Password=#pass;");
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassTextBox.Text;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("No emty fields allowed. Try again...");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Invalid e-mail or password. Try again...";
}
}
}
Complete working solution:
using MySql.Data.MySqlClient;
namespace Project
{
public sealed partial class MainPage : Page
{
const string connString = "server=server_name;user id=uid;pwd=password;persistsecurityinfo=True;database=db_name";
public MainPage()
{
this.InitializeComponent();
}
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connString))
using (MySqlCommand cmd = new MySqlCommand("SELECT " +
"Username, Password " +
"FROM users " +
"WHERE Username=#user AND Password=#pass;", conn))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
cmd.Connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassBox.Password;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("Your text");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Your text";
}
}
}
}

ASP.NET C# Validating username and password

Im trying to validate username and password from an MySql server. Login validation is working, but I can't for the life of me figure out why the "Create new user" validation isn't working.
Here are the code for registering new user. What happens is;
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
Seems like this part ^ is ruining it for me somehow, whenever i test run this code I get this message.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=user; Password=password";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
EDIT:
If I try it like this:
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
String sql = "SELECT * FROM user";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect);
da = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
ds = new DataSet("TEST");
da.Fill(ds, "user");
Response.Write(ds.Tables["user"].Rows.Count);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
This ends up with the possibility of making a user without username or password.
There are a number of things that could be going wrong. You should examine the exception.message to get insights as to what it could be.
For example, put a break point in the catch statement and see if the exception thrown for things like... does the username already exist and SQL is throwing an error. ... or are the username/password null, too long, etc...
Regardless, change the catch statement to catch(Exception exception) and see what the exception is.
I want to thank everyone for trying, found a working solution, will post it here for future reference.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
if (!string.IsNullOrWhiteSpace(inputUser.Text) && !string.IsNullOrWhiteSpace(inputPw.Text))
{
dbconnect.Open();
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
string qry = "INSERT INTO user(username, password) VALUES (#un, #pw)";
cmd = new MySqlCommand(qry, dbconnect);
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
cmd.ExecuteNonQuery();
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}

Drop-down list property [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I was wondering if somebody could point me in the right direction.My program has 1 dropdown list, 2 text boxes and 2 buttons.
namespace passwordReset
{
public partial class Form1 : Form
{
//variables to mess with the password
public string password1;
public string password2;
public string username;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(xxxxxxx);
connection.Open();
string query = "select Login, Password from Employees order by Login desc";
SqlDataAdapter da = new SqlDataAdapter(query, connection);
DataSet ds = new DataSet();
da.Fill(ds, "Credentials");
ddlLogin.DisplayMember = "Login";
ddlLogin.ValueMember = "Password";
ddlLogin.DataSource = ds.Tables["Credentials"];
connection.Close();
}
private void ddlLogin_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLogin.SelectedItem != null)
{
DataRowView drv = ddlLogin.SelectedItem as DataRowView;
//MessageBox.Show("The username you selected is: " + drv.Row["Login"].ToString());
//MessageBox.Show("The password you selected is: " + drv.Row["Password"].ToString());
//MessageBox.Show("username selected is: " + ddlLogin.Text.ToString());
//MessageBox.Show("password is: " + ddlLogin.SelectedValue.ToString());
}
}
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxx" && ddlLogin.Text != "xxxxx")
{
string newPassword = txtPassword2.Text;
username = ddlLogin.Text.ToString();
string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The code does what it needs to do, when a user selects a user name from the dropdown menu, they can reset the user's password.But if the user types the username they want to reset, I get an error here:
string currentPassword = ddlLogin.SelectedValue.ToString();
the error says Object reference not set to an instance of an object.use the "new" keyword to create an object instance.I understand the error is coming from the fact that the user is inputting the username instead of selecting it. my question is and I don't need code, I want to understand how I can go ahead and handle that, where the user wants to just type the username or pick it from the dropdown?any advise to rewrite the code is welcome, I am an entry level developer.
update, I can't answer my own question, but it works now thanks all
All,
thank you for your help.
what you all said worked, and I also had to do 1 change to my code, I realized I was doing something very dumb:
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.SelectedValue == null)
{
username = ddlLogin.Text.ToString();
}
else
{
username = ddlLogin.Text.ToString();
}
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxxx" && ddlLogin.Text != "xxxxxx")
{
string newPassword = txtPassword2.Text;
//username = ddlLogin.Text.ToString();
// string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I don't know why I did this:
string currentPassword = ddlLogin.SelectedValue.ToString();
If you don't select an item from the DropDown, it's SelectedValue will be null. You should check if it's null. If it is null then get the value from the textbox.
string userName;
if (ddlLogin.SelectedValue == null) {
userName = theTextBox.Text;
} else {
username = theDropDownList.SelectedValue.Text;
}
I'm not sure if it's the username you're trying to get. You mention the exception throws when you type the username but you grab a password from ddlLogin? Whatever you're trying to assign, just check if the dropdown is null like above and assign to the correct variable.

Connection to the database will execute only if the username is same with the database had

I got a problem here with Log on the User. Whenever I run the program, the program will not execute the Wait form, unless the Username is same with the database had.
I want to whenever the user enter the different Username with the database, the Wait form will execute too, not only when the Username is same with the database had.
Here is the code:
private void CheckUserDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT * FROM [Member] WHERE [Username] = #Username";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
_wait.ShowDialog();
UserInformation.CurrentLoggedInUserLanguage = comboBox1.Text;
UserInformation.Password = (string)dReader["Password"];
isValidPassword = BCrypt.CheckPassword(this.textBox2.Text, UserInformation.Password);
if (isValidPassword)
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
DialogResult _dialogResult = MessageBox.Show("Verified", "Congratulations", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
UserInformation.CurrentLoggedInName = (string)dReader["ChosenName"];
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
UserInformation.CurrentLoggedInUserStore = (string)dReader["UserStore"];
this.Hide();
Choices _choices = new Choices();
_choices.ShowDialog();
this.Close();
}
}
else if (!isValidPassword)
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
DialogResult _dialogResult = MessageBox.Show("Not Verified", "Warning", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
}
}
dReader.Close();
}
}
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
CheckUserDatabase(sender, e);
}
Here is the image:
Info: this.textBox2.Text is the Password Text Box, and this.textBox1.Text is the Username Text Box, and button1_Click is the Log on button.
Note: the _wait.ShowDialog is the Wait form like the image below:
Change this:
private void button1_Click(object sender, EventArgs e)
{
CheckUserDatabase(sender, e);
}
To this:
private void button1_Click(object sender, EventArgs e)
{
_wait.ShowDialog();
CheckUserDatabase(sender, e);
}
and remove _wait.ShowDialog(); from the CheckUserDatabase() method.

Validate Login Errors

I am using the following C# code for a Login Page but I get an error that says:
"Please make sure that the username and the password is Correct"
protected void btnlogin_Click(object sender, EventArgs e)
{
int Results = 0;
if (txtUsername.Text != string.Empty && txtPassword.Text != string.Empty)
{
Results = Validate_Logon(txtUsername.Text.Trim(), txtPassword.Text.Trim());
if (Results == 1)
{
lblMessage.Text = "Login is Good, Send the User to another page or enable controls";
}
else
{
lblMessage.Text = "Invalid Login";
lblMessage.ForeColor = System.Drawing.Color.Red;
//Dont Give too much information this might tell a hacker what is wrong in the login
}
}
else
{
lblMessage.Text = "Please make sure that the username and the password is Correct";
}
}
public int Validate_Logon(String Username, String Password)
{
SqlConnection con = new SqlConnection(#"***************");
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandType = CommandType.StoredProcedure;
cmdselect.CommandText = "[dbo].[Log_Members]";
cmdselect.Parameters.Add("#Username", SqlDbType.VarChar, 256).Value = Username;
cmdselect.Parameters.Add("#UPassword", SqlDbType.VarChar, 55).Value = Password;
cmdselect.Parameters.Add("#OutRes", SqlDbType.Int, 4);
cmdselect.Parameters["#OutRes"].Direction = ParameterDirection.Output;
cmdselect.Connection = con;
int Results = 0;
try
{
con.Open();
cmdselect.ExecuteNonQuery();
Results = (int)cmdselect.Parameters["#OutRes"].Value;
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
return Results;
}
Please I need to know what is wrong with the code above
It is very straightforward:
if (txtUsername.Text != string.Empty && txtPassword.Text != string.Empty)
This line is returning false, so the else executes, which is:
else
{
lblMessage.Text = "Please make sure that the username and the password is Correct";
}
Debug your code.
Well, why don't you check that the you actually entered text into both the username and the password text boxes?

Categories

Resources