Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hash password in .net core that equal in .net framework

I'm currently migrating the old API that use .Net Framework 4.5.2 to .Net Core 2.1, in the old API that use .Net Framework 4.5.2 there's this script :

PasswordHasher hasher = new PasswordHasher();
password = ConfigurationManager.AppSettings["userDefaultPassword"].ToString();
hashedPassword = hasher.HashPassword(password);

so i want to know, is there any equal function that i can use in .Net Core 2.1 that produce the same hash result as in the old .Net Framework?

like image 358
Sandy Rizky Avatar asked Dec 06 '18 04:12

Sandy Rizky


1 Answers

I believe that the equivalent is this:

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);

Notes:

  • You should now use IConfiguration (Configuration in Startup.cs) rather than ConfigurationManager.
  • PasswordHasher now takes your user object as a generic parameter (and an instance when calling HashPassword).
  • I've specified CompatibilityMode for IdentityV2 since it sounds like you want to generate backwards-compatible password hashes (i.e. you can access the database from .NET Framework and understand the hashes generated by .NET Core). If this isn't the case, you can remove it since the verification code can verify older hashes without setting this.
  • OptionsWrapper is under the Microsoft.Extensions.Options namespace.
like image 155
DiplomacyNotWar Avatar answered Oct 23 '22 17:10

DiplomacyNotWar