using System; using System.Security.Cryptography; using Microsoft.AspNetCore.Cryptography.KeyDerivation; namespace SecureCore { public class Authentication { private static int Iterations { get; set; } = 100000; private static KeyDerivationPrf KeyType { get; } = KeyDerivationPrf.HMACSHA512; private static int KeySize { get; } = 512 / 8; private static int SaltSize { get; } = 128 / 8; //128 bit salt private static int SessionKeySize { get; } = 32; //32 bytes public static string CreateSessionToken() { var token = new byte[SessionKeySize]; GetRandomBytes(ref token); return Convert.ToBase64String(token); } public static (string Hash, string Salt) HashPassword(string password) { var salt = new byte[SaltSize]; 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); } private static string GetPasswordHash(string password, byte[] salt) { return Convert.ToBase64String(KeyDerivation.Pbkdf2(password, salt, KeyType, Iterations, KeySize)); } private static void GetRandomBytes(ref byte[] bytes) { using var rng = RandomNumberGenerator.Create(); rng.GetBytes(bytes); } } public class LoginInfo { public string UserName { get; set; } public string Password { get; set; } } }