53 lines
1.6 KiB
C#
53 lines
1.6 KiB
C#
namespace Microsoft.AspNetCore.Identity
|
|
{
|
|
/// <summary>
|
|
/// Provides password hashing and verification methods.
|
|
/// </summary>
|
|
public static class PasswordHelper
|
|
{
|
|
/// <summary>
|
|
/// Hashes a password.
|
|
/// </summary>
|
|
/// <param name="plainPassword">The plain password.</param>
|
|
/// <returns></returns>
|
|
public static string HashPassword(string plainPassword)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(plainPassword))
|
|
return plainPassword?.Trim();
|
|
|
|
var ph = new PasswordHasher<object>();
|
|
return ph.HashPassword(null, plainPassword.Trim());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifies a password with a hashed version.
|
|
/// </summary>
|
|
/// <param name="plainPassword">The plain password.</param>
|
|
/// <param name="hashedPassword">The password hash.</param>
|
|
/// <param name="rehashNeeded">A value indicating whether the password needs a rehash.</param>
|
|
/// <returns></returns>
|
|
public static bool VerifyPassword(string plainPassword, string hashedPassword, out bool rehashNeeded)
|
|
{
|
|
rehashNeeded = false;
|
|
if (string.IsNullOrWhiteSpace(plainPassword) || string.IsNullOrWhiteSpace(hashedPassword))
|
|
return false;
|
|
|
|
var ph = new PasswordHasher<object>();
|
|
var result = ph.VerifyHashedPassword(null, hashedPassword, plainPassword);
|
|
switch (result)
|
|
{
|
|
case PasswordVerificationResult.Success:
|
|
return true;
|
|
|
|
case PasswordVerificationResult.SuccessRehashNeeded:
|
|
rehashNeeded = true;
|
|
return true;
|
|
|
|
case PasswordVerificationResult.Failed:
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|