forked from mtusi2026/mtusi2026lab3
Добавить балансировку и идемпотентность для лабораторной 3.
Две реплики API за HAProxy, общий PostgreSQL и повтор сообщения без дубля.
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Konscious.Security.Cryptography;
|
||||
|
||||
namespace Messenger;
|
||||
|
||||
public static class Passwords
|
||||
{
|
||||
private const int MemoryKb = 19456;
|
||||
private const int Iterations = 2;
|
||||
private const int Parallelism = 1;
|
||||
private const int HashLength = 32;
|
||||
private const int SaltLength = 16;
|
||||
|
||||
public static readonly string DummyHash = Hash("dummy-password-not-a-login");
|
||||
|
||||
public static string Hash(string password)
|
||||
{
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltLength);
|
||||
var hash = Derive(password, salt);
|
||||
return $"argon2id$m={MemoryKb},t={Iterations},p={Parallelism}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
|
||||
}
|
||||
|
||||
public static bool Verify(string password, string stored)
|
||||
{
|
||||
var parts = stored.Split('$');
|
||||
if (parts.Length != 4 || parts[0] != "argon2id")
|
||||
return false;
|
||||
byte[] salt;
|
||||
byte[] expected;
|
||||
try
|
||||
{
|
||||
salt = Convert.FromBase64String(parts[2]);
|
||||
expected = Convert.FromBase64String(parts[3]);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var actual = Derive(password, salt);
|
||||
return CryptographicOperations.FixedTimeEquals(actual, expected);
|
||||
}
|
||||
|
||||
private static byte[] Derive(string password, byte[] salt)
|
||||
{
|
||||
using var argon = new Argon2id(Encoding.UTF8.GetBytes(password))
|
||||
{
|
||||
Salt = salt,
|
||||
MemorySize = MemoryKb,
|
||||
Iterations = Iterations,
|
||||
DegreeOfParallelism = Parallelism
|
||||
};
|
||||
return argon.GetBytes(HashLength);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user