40 lines
1.3 KiB
C#
40 lines
1.3 KiB
C#
using System;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace UserPermissionTest_CS_WinForms
|
|
{
|
|
public static class PasswordHasher
|
|
{
|
|
/// <summary>
|
|
/// Hashes the plain-text password using SHA-256.
|
|
/// </summary>
|
|
public static string HashPassword(string password)
|
|
{
|
|
if (password == null) throw new ArgumentNullException(nameof(password));
|
|
|
|
using (SHA256 sha256 = SHA256.Create())
|
|
{
|
|
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
|
|
StringBuilder builder = new StringBuilder();
|
|
for (int i = 0; i < bytes.Length; i++)
|
|
{
|
|
builder.Append(bytes[i].ToString("x2"));
|
|
}
|
|
return builder.ToString();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifies whether the entered plain-text password matches the stored SHA-256 hash.
|
|
/// </summary>
|
|
public static bool VerifyPassword(string enteredPassword, string storedHash)
|
|
{
|
|
if (enteredPassword == null || storedHash == null) return false;
|
|
|
|
string hashedInput = HashPassword(enteredPassword);
|
|
return hashedInput.Equals(storedHash, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
}
|
|
}
|