How to hash a password

后端 未结 9 843
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:49

I\'d like to store the hash of a password on the phone, but I\'m not sure how to do it. I can only seem to find encryption methods. How should the password be hashed properl

9条回答
  •  天命终不由人
    2020-11-22 15:13

    In ASP.NET Core, use PasswordHasher.
     • Namespace: Microsoft.AspNetCore.Identity
     • Assembly: Microsoft.Extensions.Identity.Core.dll (NuGet | Source)


    To hash a password, use HashPassword():

    var hashedPassword = new PasswordHasher().HashPassword(null, password);
    

    To verify a password, use VerifyHashedPassword():

    var passwordVerificationResult = new PasswordHasher().VerifyHashedPassword(null, hashedPassword, password);
    switch (passwordVerificationResult)
    {
        case PasswordVerificationResult.Failed:
            Console.WriteLine("Password incorrect.");
            break;
        
        case PasswordVerificationResult.Success:
            Console.WriteLine("Password ok.");
            break;
        
        case PasswordVerificationResult.SuccessRehashNeeded:
            Console.WriteLine("Password ok but should be rehashed and updated.");
            break;
        
        default:
            throw new ArgumentOutOfRangeException();
    }
    
    

    Pros:

    • Part of the .NET platform. Much safer and trustworthier than building your own crypto algorithm.
    • Configurable iteration count and future compatibility (see PasswordHasherOptions).
    • Took Timing Attack into consideration when verifying password (source), just like what PHP and Go did.

    Cons:

    • Hashed password format incompatible with those hashed by other libraries or in other languages.

提交回复
热议问题