Files
SE-UGW/src/Gateway.Api/Services/PasswordService.cs
T
2026-10-08 10:20:30 +02:00

35 lines
1.2 KiB
C#

using System.Security.Cryptography;
namespace Gateway.Api.Services;
public sealed class PasswordService
{
private const int SaltLength = 16;
private const int HashLength = 32;
private const int Iterations = 310_000;
public PasswordHash Create(string password)
{
ValidatePassword(password);
var salt = RandomNumberGenerator.GetBytes(SaltLength);
var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, Iterations, HashAlgorithmName.SHA512, HashLength);
return new PasswordHash(hash, salt, Iterations);
}
public bool Verify(string password, byte[] expectedHash, byte[] salt, int iterations)
{
var candidate = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, expectedHash.Length);
return CryptographicOperations.FixedTimeEquals(candidate, expectedHash);
}
public static void ValidatePassword(string password)
{
if (string.IsNullOrWhiteSpace(password) || password.Length < 12)
{
throw new DomainValidationException("Das Passwort muss mindestens 12 Zeichen haben.");
}
}
}
public sealed record PasswordHash(byte[] Hash, byte[] Salt, int Iterations);