galaeth-draft/Galaeth.Services/Services/CryptographyService.cs

67 lines
2.2 KiB
C#
Raw Normal View History

2024-11-17 10:31:01 +01:00
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;
/// <inheritdoc />
[RegisterSingleton]
public class CryptographyService : ICryptographyService
{
private readonly PwdHashConfiguration _configuration;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyService"/> class.
/// </summary>
/// <param name="pwdHashSettings">Instance of <see cref="IOptions{PwdHashConfiguration}"/>.</param>
public CryptographyService(IOptions<PwdHashConfiguration> pwdHashSettings)
{
_configuration = pwdHashSettings.Value;
}
/// <inheritdoc/>
public byte[] GenerateSalt(int? size = null)
{
var result = RandomNumberGenerator.GetBytes(size ?? _configuration.SaltSize);
return result;
}
/// <inheritdoc/>
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;
}
/// <inheritdoc/>
public bool VerifyPassword(string password, byte[] salt, byte[] passwordHash)
{
var checkHash = HashPassword(password, salt);
return passwordHash.SequenceEqual(checkHash);
}
/// <inheritdoc/>
public bool VerifyPassword(string password, string salt, string passwordHash)
{
var checkHash = HashPassword(password, Convert.FromBase64String(salt));
return Convert.FromBase64String(passwordHash).SequenceEqual(checkHash);
}
/// <inheritdoc/>
public string GenerateRandomString(int length)
{
const string availableChars = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
return RandomNumberGenerator.GetString(availableChars, length);
}
}