using Microsoft.AspNetCore.Identity; using Store.Users.Entities; namespace Store.Users.Services; /// 新密码使用带盐哈希;兼容旧 wxxd.user 的明文密码,登录验证不修改密码。 public static class UserPassword { private static readonly PasswordHasher Hasher = new(); public static string Hash(UserEntity user, string password) => Hasher.HashPassword(user, password); public static bool Verify(UserEntity user, string password) { if (string.IsNullOrEmpty(user.Password) || string.IsNullOrEmpty(password)) return false; // Identity 的密码以固定的版本字节开头,格式损坏时拒绝验证。 if (user.Password.StartsWith("AQAAAA", StringComparison.Ordinal) || user.Password.StartsWith("AA", StringComparison.Ordinal)) { try { return Hasher.VerifyHashedPassword(user, user.Password, password) != PasswordVerificationResult.Failed; } catch (FormatException) { return false; } } return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( System.Text.Encoding.UTF8.GetBytes(user.Password), System.Text.Encoding.UTF8.GetBytes(password)); } }