| 12345678910111213141516171819202122232425262728293031323334 |
- using System;
- using System.Security.Cryptography;
- using System.Text;
- namespace WpfApp1.Helpers
- {
- public static class PasswordHelper
- {
- private const int SaltSize = 16;
- private const int HashSize = 32;
- private const int Iterations = 100_000;
- public static string HashPassword(string password)
- {
- byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
- byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
- Encoding.UTF8.GetBytes(password), salt, Iterations, HashAlgorithmName.SHA256, HashSize);
- return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
- }
- public static bool VerifyPassword(string password, string storedHash)
- {
- string[] parts = storedHash.Split(':');
- if (parts.Length != 2) return false;
- byte[] salt = Convert.FromBase64String(parts[0]);
- byte[] expectedHash = Convert.FromBase64String(parts[1]);
- byte[] actualHash = Rfc2898DeriveBytes.Pbkdf2(
- Encoding.UTF8.GetBytes(password), salt, Iterations, HashAlgorithmName.SHA256, HashSize);
- return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
- }
- }
- }
|