Выполнениие лабораторной работы на 5, трек 2.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
using Isopoh.Cryptography.Argon2;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class Argon2PasswordHasher : IPasswordHasher
|
||||
{
|
||||
// Минимум по рекомендации OWASP для Argon2id: m=19 MiB, t=2, p=1. Обоснование и выбор — в REPORT.md.
|
||||
private const int TimeCost = 2;
|
||||
private const int MemoryCostKiB = 19 * 1024;
|
||||
private const int Parallelism = 1;
|
||||
|
||||
// Каждое вычисление занимает ~19 MiB и ядро CPU: без лимита 100 параллельных входов = ~2 GiB памяти.
|
||||
private const int MaxConcurrency = 4;
|
||||
private static readonly TimeSpan SlotWaitTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly SemaphoreSlim _slots = new(MaxConcurrency, MaxConcurrency);
|
||||
|
||||
// Хеш от случайного пароля, который никто не знает. Нужен только для выравнивания времени при неизвестном username.
|
||||
private readonly string _dummyHash;
|
||||
|
||||
public Argon2PasswordHasher()
|
||||
{
|
||||
_dummyHash = HashCore(Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)));
|
||||
}
|
||||
|
||||
public async Task<string> HashAsync(string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => HashCore(password), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyAsync(string? hash, string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var ok = Argon2.Verify(hash ?? _dummyHash, password, secret: null, secureArrayCall: null);
|
||||
return hash is not null && ok;
|
||||
}, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcquireSlotAsync(CancellationToken ct)
|
||||
{
|
||||
if (!await _slots.WaitAsync(SlotWaitTimeout, ct))
|
||||
{
|
||||
throw new PasswordHasherBusyException();
|
||||
}
|
||||
}
|
||||
|
||||
// HybridAddressing — это Argon2id. Соль генерируется библиотекой и входит в возвращаемую строку.
|
||||
private static string HashCore(string password) =>
|
||||
Argon2.Hash(password, TimeCost, MemoryCostKiB, Parallelism, Argon2Type.HybridAddressing);
|
||||
}
|
||||
Reference in New Issue
Block a user