I read the code again and again to find out where the error occurs, but I cannot find it. I copied this code from stackoverflow, which never tested it or did not understand how to fix it. I get passwords from a web service, hashing, salting and saving it on SqlServer 2008. Variables on SqlServer are declared as mail as nvarchar (64), hash as varbinary (128) and salt as varbinary (128). Passwords are saved, but when I try to verify the password is correct, the method always returns false. These are my methods.
public int InsertData(string mail,string Password)
{
int lineas;
UserData usuario = HashPassword(Password);
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Usuarios (Mail,Hash,Salt) VALUES (@mail,@hash,@salt)";
command.Parameters.AddWithValue("@mail", mail);
command.Parameters.AddWithValue("@hash", usuario.Password);
command.Parameters.AddWithValue("@salt", usuario.salt);
connection.Open();
lineas=command.ExecuteNonQuery();
}
usuario = null;
return lineas;
}
private UserData HashPassword(string Password)
{
using (var deriveBytes = new Rfc2898DeriveBytes(Password, 20))
{
byte[] salt = deriveBytes.Salt;
byte[] key = deriveBytes.GetBytes(20);
UserData usuario = new UserData();
usuario.Password = key;
usuario.salt = salt;
return usuario;
}
}
And the next method is the one I use to verify the password, it always returns false
private bool CheckPassword(string Password, byte[] hash, byte[] salt)
{
using (var deriveBytes = new Rfc2898DeriveBytes(Password, salt))
{
byte[] newKey = deriveBytes.GetBytes(20);
if (!newKey.SequenceEqual(hash))
return false;
else
return true;
}
}
This method retrieves registration information.
public bool ValidateLogIn(string mail, string Password)
{
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "Select * from Usuarios where Mail=@mail";
command.Parameters.AddWithValue("@mail",mail);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
reader.Read();
byte[] hash = (byte[])reader["Hash"];
byte[] salt = (byte[])reader["Salt"];
if(CheckPassword(Password,hash,salt))
{
/
UpdateData(mail, Password);
return true;
}
else
{
return false;
}
}
}
}
Any ideas what could be wrong?
EDIT: ,
qaru.site/questions/132067/...