HRM-10/HRM.UI/Helpers/PasswordResetTokenHelper.cs
2026-11-24 12:01:14 +06:00

126 lines
4.8 KiB
C#

using System;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
namespace HRM.UI.Helpers
{
/// <summary>
/// Data carried (encrypted) inside the password reset link.
/// </summary>
public class PasswordResetTokenData
{
public int UserID { get; set; }
public int UserType { get; set; }
// Expiry, Unix time (seconds, UTC)
public long ExpiresAt { get; set; }
// Fingerprint of the password at the time the link was made - changes once the password
// is reset, so a link works only once.
public string Stamp { get; set; }
}
/// <summary>
/// Builds and reads the password reset link token.
/// The token is AES-256-GCM encrypted (confidential + tamper-proof) with a key derived from
/// AppSettings.Secret, and URL-safe Base64 encoded: nonce(12) | tag(16) | cipher text.
/// </summary>
public static class PasswordResetTokenHelper
{
private const int NonceSize = 12;
private const int TagSize = 16;
private const string KeyPurpose = "|HRM.ForgotPassword.ResetLink.v1";
public static string CreateToken(string secret, PasswordResetTokenData data)
{
byte[] plain = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
byte[] nonce = RandomNumberGenerator.GetBytes(NonceSize);
byte[] cipher = new byte[plain.Length];
byte[] tag = new byte[TagSize];
using (AesGcm aes = new AesGcm(DeriveKey(secret), TagSize))
{
aes.Encrypt(nonce, plain, cipher, tag);
}
byte[] token = new byte[NonceSize + TagSize + cipher.Length];
Buffer.BlockCopy(nonce, 0, token, 0, NonceSize);
Buffer.BlockCopy(tag, 0, token, NonceSize, TagSize);
Buffer.BlockCopy(cipher, 0, token, NonceSize + TagSize, cipher.Length);
return ToBase64Url(token);
}
/// <summary>
/// Decrypts the token. Returns null when it is malformed, was changed, or was not made by this server.
/// (Expiry is checked by the caller so it can show a separate "expired" message.)
/// </summary>
public static PasswordResetTokenData ReadToken(string secret, string token)
{
try
{
if (string.IsNullOrWhiteSpace(token)) return null;
byte[] raw = FromBase64Url(token.Trim());
if (raw.Length <= NonceSize + TagSize) return null;
byte[] nonce = new byte[NonceSize];
byte[] tag = new byte[TagSize];
byte[] cipher = new byte[raw.Length - NonceSize - TagSize];
Buffer.BlockCopy(raw, 0, nonce, 0, NonceSize);
Buffer.BlockCopy(raw, NonceSize, tag, 0, TagSize);
Buffer.BlockCopy(raw, NonceSize + TagSize, cipher, 0, cipher.Length);
byte[] plain = new byte[cipher.Length];
using (AesGcm aes = new AesGcm(DeriveKey(secret), TagSize))
{
aes.Decrypt(nonce, cipher, tag, plain);
}
return JsonConvert.DeserializeObject<PasswordResetTokenData>(Encoding.UTF8.GetString(plain));
}
catch (Exception)
{
// CryptographicException (tampered / wrong key), FormatException, JsonException ...
return null;
}
}
/// <summary>
/// Fingerprint of the user's current (stored, encrypted) password.
/// </summary>
public static string CreateStamp(int userId, string storedPassword)
{
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(userId + "|" + (storedPassword ?? string.Empty)));
return Convert.ToHexString(hash, 0, 16);
}
public static bool IsSameStamp(string a, string b)
{
if (a == null || b == null) return false;
return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b));
}
private static byte[] DeriveKey(string secret)
{
if (string.IsNullOrEmpty(secret))
throw new InvalidOperationException("AppSettings.Secret is not configured.");
return SHA256.HashData(Encoding.UTF8.GetBytes(secret + KeyPurpose));
}
private static string ToBase64Url(byte[] data)
{
return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
private static byte[] FromBase64Url(string data)
{
string s = data.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2: s += "=="; break;
case 3: s += "="; break;
}
return Convert.FromBase64String(s);
}
}
}