如何在.net框架中等于.net核心中的密码

San*_*zky 5 .net c# .net-core asp.net-core-2.0

我目前正在将使用.Net Framework 4.5.2的旧API迁移到.Net Core 2.1,在使用.Net Framework 4.5.2的旧API中有以下脚本:

PasswordHasher hasher = new PasswordHasher();
password = ConfigurationManager.AppSettings["userDefaultPassword"].ToString();
hashedPassword = hasher.HashPassword(password);
Run Code Online (Sandbox Code Playgroud)

所以我想知道,是否有任何相同的功能,我可以在.Net Core 2.1中使用,产生与旧.Net框架相同的哈希结果?

Joh*_*ica 7

我相信这相当于:

IConfiguration _configuration;
PasswordHasher<User> hasher = new PasswordHasher<User>(
    new OptionsWrapper<PasswordHasherOptions>(
        new PasswordHasherOptions() {
            CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
    })
);
password = _configuration["userDefaultPassword"].ToString();
hashedPassword = hasher.HashPassword(user, password);
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您现在应该使用IConfiguration(Configuration在Startup.cs中)而不是ConfigurationManager.
  • PasswordHasher现在将您的用户对象作为通用参数(以及调用HashPassword时的实例).
  • 我已经指定了CompatibilityMode,IdentityV2因为它听起来像是要生成向后兼容的密码哈希(即,您可以从.NET Framework访问数据库并了解.NET Core生成的哈希).如果不是这种情况,您可以将其删除,因为验证码可以在不设置此值的情况下验证较旧的哈希值.
  • OptionsWrapperMicrosoft.Extensions.Options命名空间下.