Hashing passwords in .NET Core offers several benefits that are crucial for ensuring the security of user accounts and sensitive information in applications.
Custom Password Validation Attribute
The CustomPasswordValidationAttribute
class is designed to provide custom validation for password fields in .NET Core applications. It allows developers to enforce specific requirements or constraints on passwords, such as minimum length, inclusion of special characters, or absence of common patterns.
public class CustomPasswordValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var password = value as string;
if (password == null)
return false;
if (password.Length < 8)
return false;
if (!password.Any(char.IsUpper))
return false;
if (!password.Any(char.IsDigit))
return false;
if (!password.Any(c => !char.IsLetterOrDigit(c)))
return false;
return true;
}
}
Protection Against Unauthorized Access
Hashing passwords ensures that even if the hashed passwords are compromised, the original passwords cannot be easily retrieved. This helps prevent unauthorized access to user accounts and sensitive data.
public class PasswordHasher
{
public static string HashPassword(string? password)
{
using (SHA256 sha256 = SHA256.Create())
{
// Compute hash from password
byte[] hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashedBytes.Length; i++)
{
//converted to its hexadecimal representation using the ToString("x2")
builder.Append(hashedBytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}