Я создал систему входа в систему для проекта, над которым я работал, и пока он работает, похоже, это не самый эффективный способ сделать это. Это проект WPF / C#, связанный с базой данных SQLite, которая использует LINQ для запросов. В идеале я хотел бы, чтобы запрос выдавал одну переменную типа string, чтобы я мог манипулировать ею и сравнивать ее с тем, что вводит пользователь.
List<Engineer> engineers;
private void LoginButton_Click(object sender, RoutedEventArgs e)
{
string username = UsernameField.Text;
string password = PasswordField.Password.ToString();
string hashedPasswordString = "";
string saltString = "";
//establishes connection
using (SQLiteConnection conn = new SQLiteConnection(App.engineerDatabasePath))
{
engineers = conn.Table<Engineer>().ToList();
//Queries for a list containing the respective hashed passwords. This will only contain one password since the emails are unique
var hashedpasswordlist = from c in engineers
where c.Email == username
select c.Password;
//Take the password in the list and assign it to a string variable that can be compared
foreach (var item in hashedpasswordlist)
{
hashedPasswordString = item;
}
//Queries for a list containing the respective salts. This will only contain one salt since the emails are unique
var saltlist = from c in engineers
where c.Email == username
select c.Salt;
//Take the salt in the list and assign it to a variable to the password input, creating a hash value that is to be assigned
foreach (var item in saltlist)
{
saltString = item;
}
//Confirmation that the implementation works as it should
if (GenerateSHA256Hash(password, saltString) == hashedPasswordString)
{
MessageBoxResult deleteConfirmation = MessageBox.Show("IT WORKS!", "Grats", MessageBoxButton.YesNo, MessageBoxImage.Warning);
}
}
//Allows you to log in regardless of whether your login details are correct. This is the case for testing purposes.
MainWindow MainWindow = new MainWindow();
MainWindow.Show();
this.Close();
}
Вот GenerateSHA256Ha sh метод и метод ByteArrayToHexString
public string GenerateSHA256Hash(string input, string salt)
{
byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
System.Security.Cryptography.SHA256Managed sha256hashtring = new System.Security.Cryptography.SHA256Managed();
byte[] hash = sha256hashtring.ComputeHash(bytes);
return ByteArrayToHexString(hash);
}
public static string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}