using System.Security.Cryptography; using System.Text; using Galaeth.Services.Configuration; using Galaeth.Services.Interfaces; using Injectio.Attributes; using Konscious.Security.Cryptography; using Microsoft.Extensions.Options; namespace Galaeth.Services.Services; /// [RegisterSingleton] public class CryptographyService : ICryptographyService { private readonly PwdHashConfiguration _configuration; /// /// Initializes a new instance of the class. /// /// Instance of . public CryptographyService(IOptions pwdHashSettings) { _configuration = pwdHashSettings.Value; } /// public byte[] GenerateSalt(int? size = null) { var result = RandomNumberGenerator.GetBytes(size ?? _configuration.SaltSize); return result; } /// public byte[] HashPassword(string password, byte[] salt) { var argon2Id = new Argon2id(Encoding.UTF8.GetBytes(password)); argon2Id.Salt = salt; argon2Id.DegreeOfParallelism = _configuration.DegreeOfParallelism; argon2Id.Iterations = _configuration.NumberOfIterations; argon2Id.MemorySize = _configuration.MemoryToUseKb; var bytes = argon2Id.GetBytes(_configuration.HashSize); GC.Collect(); return bytes; } /// public bool VerifyPassword(string password, byte[] salt, byte[] passwordHash) { var checkHash = HashPassword(password, salt); return passwordHash.SequenceEqual(checkHash); } /// public bool VerifyPassword(string password, string salt, string passwordHash) { var checkHash = HashPassword(password, Convert.FromBase64String(salt)); return Convert.FromBase64String(passwordHash).SequenceEqual(checkHash); } /// public string GenerateRandomString(int length) { const string availableChars = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789"; return RandomNumberGenerator.GetString(availableChars, length); } }