PasswordHelper.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace WpfApp1.Helpers
  5. {
  6. public static class PasswordHelper
  7. {
  8. private const int SaltSize = 16;
  9. private const int HashSize = 32;
  10. private const int Iterations = 100_000;
  11. public static string HashPassword(string password)
  12. {
  13. byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
  14. byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
  15. Encoding.UTF8.GetBytes(password), salt, Iterations, HashAlgorithmName.SHA256, HashSize);
  16. return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
  17. }
  18. public static bool VerifyPassword(string password, string storedHash)
  19. {
  20. string[] parts = storedHash.Split(':');
  21. if (parts.Length != 2) return false;
  22. byte[] salt = Convert.FromBase64String(parts[0]);
  23. byte[] expectedHash = Convert.FromBase64String(parts[1]);
  24. byte[] actualHash = Rfc2898DeriveBytes.Pbkdf2(
  25. Encoding.UTF8.GetBytes(password), salt, Iterations, HashAlgorithmName.SHA256, HashSize);
  26. return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
  27. }
  28. }
  29. }