using Microsoft.AspNetCore.Cryptography.KeyDerivation; using System.Security.Cryptography; namespace AyCode.Utils.Helpers { public class PasswordHasher { public string HashPassword(string password) { // Generate a random salt byte[] salt = new byte[16]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } // Hash the password with the salt string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 32)); // Combine the salt and hashed password string combinedHash = $"$bcrypt$v=1$salt={Convert.ToBase64String(salt)}$hash={hashedPassword}"; return combinedHash; } public bool VerifyPassword(string password, string hashedPassword) { // Extract the salt and hashed password from the combined hash string[] parts = hashedPassword.Split('$'); byte[] salt = Convert.FromBase64String(parts[3]); string storedHash = parts[5]; // Hash the provided password with the extracted salt string hashedProvidedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 32)); // Compare the hashed passwords return storedHash == hashedProvidedPassword; } } }