Files
WorkFlowCheck/src/WorkFlowCheck.Common/Security/PasswordHasher.cs
T
2026-09-12 18:19:29 +02:00

58 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.Security
{
public static class PasswordHasher
{
// Jelszó hashelése
private const string _saltstring = "xc45DDfrt!!ED210:";
public static string HashPassword(string password)
{
// Generate a random salt
byte[] salt = Encoding.UTF8.GetBytes(_saltstring);
// Hash the password with the salt
using (var rfc2898 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256))
{
byte[] hash = rfc2898.GetBytes(32); // 256-bit hash
byte[] hashBytes = new byte[48]; // Salt (16 bytes) + Hash (32 bytes)
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 32);
return Convert.ToBase64String(hashBytes);
}
}
// Jelszó ellenőrzése
public static bool VerifyPassword(string storedPasswordHash, string inputPassword)
{
var inputPasswordHash = HashPassword(inputPassword);
byte[] hashBytes = Convert.FromBase64String(storedPasswordHash);
// Extract salt (first 16 bytes) and stored hash (next 32 bytes)
byte[] salt = Encoding.UTF8.GetBytes(_saltstring);
byte[] storedHash = new byte[32];
Array.Copy(hashBytes, 0, salt, 0, 16);
Array.Copy(hashBytes, 16, storedHash, 0, 32);
// Hash the input password with the same salt
using (var rfc2898 = new Rfc2898DeriveBytes(inputPassword, salt, 10000, HashAlgorithmName.SHA256))
{
byte[] inputHash = rfc2898.GetBytes(32);
// Compare the stored hash and the calculated hash
return CryptographicOperations.FixedTimeEquals(storedHash, inputHash);
}
}
}
}