69 lines
1.6 KiB
C#
69 lines
1.6 KiB
C#
using System;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
using TextSender_API.Models;
|
|
using TextSender_API.Repositories;
|
|
|
|
namespace TextSender_API.Controllers;
|
|
|
|
public class PasswordVerification
|
|
{
|
|
#region Fiends
|
|
private UsersRepository? _userRepo;
|
|
private SaltRepository? _saltRepo;
|
|
private int _keySize = 64;
|
|
private int _iterations = 350000;
|
|
#endregion
|
|
|
|
#region Constructors
|
|
public PasswordVerification()
|
|
{
|
|
}
|
|
|
|
public PasswordVerification(UsersRepository userRepo, SaltRepository saltRepo)
|
|
{
|
|
this._userRepo = userRepo;
|
|
this._saltRepo = saltRepo;
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
public bool VerifyPassword(User user, string password)
|
|
{
|
|
var salt = this._saltRepo.Retrieve(user.Id);
|
|
var hashedPassword = this.HashPassword(user, salt, password);
|
|
|
|
return hashedPassword.Equals(user.Password);
|
|
}
|
|
public Salt CreateSalt(User user)
|
|
{
|
|
var salt = new Salt();
|
|
salt.Key = RandomNumberGenerator.GetBytes(this._keySize);
|
|
|
|
return salt;
|
|
}
|
|
|
|
public string HashPassword(User user, Salt salt, string password = "")
|
|
{
|
|
var hashAlgorithm = HashAlgorithmName.SHA512;
|
|
var dbHashedPassword = user.Password;
|
|
|
|
if (!string.IsNullOrEmpty(password))
|
|
{
|
|
user.Password = password;
|
|
}
|
|
|
|
var hash = Rfc2898DeriveBytes.Pbkdf2(
|
|
Encoding.UTF8.GetBytes(user.Password!),
|
|
salt.Key!,
|
|
this._iterations,
|
|
hashAlgorithm,
|
|
this._keySize);
|
|
|
|
user.Password = dbHashedPassword;
|
|
|
|
return Convert.ToHexString(hash);
|
|
}
|
|
#endregion
|
|
} |