I'm making a WinForms application, but i'm not really sure if this is a good implementation for my Login Form.
This is the algorithm for Salt Hash i use, Thanks to blowdart:
private static byte[] CreateHash(byte[] bPassword, byte[] bSalt)
{
HashAlgorithm algorithm = new SHA512Managed();
byte[] bToBeHashed = new byte[bPassword.Length + bSalt.Length];
for (int i = 0; i < bPassword.Length; i++)
bToBeHashed[i] = bPassword[i];
for (int i = 0; i < bSalt.Length; i++)
bToBeHashed[bPassword.Length + i] = bSalt[i];
return algorithm.ComputeHash(bToBeHashed);
}
This is the method i call to access the data base (SQL Server):
public int Login(string strUser, string strPassword)
{
using (IDbConnection connection = new SqlConnection(GlobalConfig.ConnectionDataBaseString(db)))
{
byte[] bSalt = new byte[8];
var parameters = new DynamicParameters();
parameters.Add("@idUser", strUser);
// dbo.spUserExists = SELECT byteSalt FROM users WHERE idUser=@idUser
var reader = connection.ExecuteReader("dbo.spUserExists", parameters, commandType: CommandType.StoredProcedure);
if (reader.Read())
{
bSalt = (byte[])reader["byteSalt"];
byte[] bPassword = Encoding.UTF8.GetBytes(strPassword); // string to byte[]
byte[] bHash = new byte[bPassword.Length + bSalt.Length];
bHash = CreateHash(bPassword, bSalt);
parameters = new DynamicParameters();
parameters.Add("@idUser", strUser);
parameters.Add("@byteHash", bHash);
reader.Dispose();
reader.Close();
// dbo.spPasswordExists = SELECT * FROM users WHERE idUser = @idUser AND byteHash = @byteHash
var reader = connection.ExecuteReader("dbo.spPasswordExists", parameters, commandType: CommandType.StoredProcedure);
if (reader.Read())
return 0; // User & Password are correct
else
return 2; // User correct, Password incorrect
}
else
return 1; // User does not exists
}
}
And this is the event when trying to Log In:
private void btnLogIn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(UserTextBox.Text))
{
MessageBox.Show("Please type your User.");
}
else if (string.IsNullOrWhiteSpace(PasswordTextBox.Text))
{
MessageBox.Show("Please type your Password.");
}
else
{
switch (Login(UserTextBox.Text, PasswordTextBox.Text))
{
case 0:
if (RememberMeCheckBox.Checked)
{
Properties.Settings.Default.UserName = UserTextBox.Text; // Remembers User name
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.UserName = null;
Properties.Settings.Default.Save();
}
UserTextBox.Clear();
PasswordTextBox.Clear();
DialogResult = DialogResult.OK;
this.Close();
break;
case 1:
MessageBox.Show("Incorrect User.");
break;
case 2:
MessageBox.Show("Incorrect Password.");
break;
}
}
}
How can i improve this or make a better solution? Making sure that is a secure log in. Sorry for bad english.