using Isopoh.Cryptography.Argon2;
using RegulatorioAuth.Application.Services.Interfaces;
using System.Security.Cryptography;
using System.Text;
namespace RegulatorioAuth.Application.Services;
public class PasswordHasherService : IPasswordHasherService
{
public (string HashedPassword, byte[] Salt) HashPassword(string password)
{
var salt = GenerateSalt();
Argon2Config argon2Config = new()
{
Type = Argon2Type.DataIndependentAddressing,
Version = Argon2Version.Nineteen,
MemoryCost = 65536,
TimeCost = 4,
Lanes = 8,
Threads = 1,
Password = Encoding.UTF8.GetBytes(password),
Salt = salt
};
using Argon2 argon2 = new(argon2Config);
using var hash = argon2.Hash();
return (argon2Config.EncodeString(hash.Buffer), salt);
}
public bool VerifyPassword(string password, string hashedPassword, byte[] salt)
{
Argon2Config configOfPasswordToVerify = new Argon2Config
{
Type = Argon2Type.DataIndependentAddressing,
Version = Argon2Version.Nineteen,
MemoryCost = 65536,
TimeCost = 4,
Lanes = 8,
Threads = 1,
Password = Encoding.UTF8.GetBytes(password),
Salt = salt
};
return Argon2.Verify(hashedPassword, configOfPasswordToVerify);
}
public byte[] GenerateSalt()
{
byte[] salt = new byte[16];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
return salt;
}
}