58 lines
1.9 KiB
C#
58 lines
1.9 KiB
C#
using System;
|
|
using System.Data.SqlClient;
|
|
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
|
|
|
|
namespace SecureCore.Authentication
|
|
{
|
|
public class PasswordManager
|
|
{
|
|
private static string ConnectionString = @"Server=DESKTOP-OEDDVKC\SQLEXPRESS;Database=main;Integrated Security=true;";
|
|
|
|
public PasswordManager()
|
|
{
|
|
}
|
|
|
|
public static (string Hash, string Salt) HashPassword(string password)
|
|
{
|
|
var salt = new byte[Settings.SaltSize];
|
|
|
|
ByteGenerator.GetRandomBytes(ref salt);
|
|
|
|
return (GetPasswordHash(password, salt), Convert.ToBase64String(salt));
|
|
}
|
|
|
|
public static bool PasswordIsValid(string password, string salt, string passwordHash)
|
|
{
|
|
var saltBytes = Convert.FromBase64String(salt);
|
|
|
|
return passwordHash == GetPasswordHash(password, saltBytes);
|
|
}
|
|
|
|
public static (string PasswordHash, string SaltHash) GetUserPasswordHash(int userId)
|
|
{
|
|
using (var connection = new SqlConnection(ConnectionString))
|
|
{
|
|
using (var command = new SqlCommand("SELECT [Password Hash], [Salt Hash] FROM Login WHERE [User Key] = @UserId", connection))
|
|
{
|
|
command.Parameters.AddWithValue("UserId", userId);
|
|
|
|
connection.Open();
|
|
|
|
var reader = command.ExecuteReader();
|
|
|
|
if (!reader.HasRows) throw new MissingFieldException("No login records exist for this user.");
|
|
|
|
reader.Read();
|
|
|
|
return (reader["Password Hash"].ToString(), reader["Salt Hash"].ToString());
|
|
}
|
|
}
|
|
}
|
|
|
|
private static string GetPasswordHash(string password, byte[] salt)
|
|
{
|
|
return Convert.ToBase64String(KeyDerivation.Pbkdf2(password, salt, Settings.KeyType, Settings.Iterations, Settings.KeySize));
|
|
}
|
|
}
|
|
}
|