How to access the SimpleMembershipProvider Hashing

2019-08-15 17:49发布

问题:

Is there a way to use the same hashing algorithm that SimpleMembership uses for password to hash a clear-text password without actually setting or changing a password? I just want the hashed version of the password for comparison.

I am building a new site using MVC 4, and have opted to use the SimpleMembershipProvider to handle most account related data. One requirement I have is to keep a password history. I do not need to be able to retrieve the actual passwords, so one-way hashing is fine.

I have come up with a solution that keeps a separate table of passwords using a separate one-way hashing algorithm, but it seems rather clunky to me. It would be far cleaner if I could take the new password, use the SimpleMembership's algorithm to hash it, compare that to my stored passwords, and then only change it if it is valid. This would also help when I go to migrate our passwords from the old site.

Right now the only way I can find to generate the hashed version of the password is by changing the password, and then reading the hashed version from SQL.

回答1:

SimpleMembershipProvider.SetPassword (the private method), uses System.Web.Helpers.Crypto.HashPassword, so you could use that to hash the password. It also takes care of the salt for you, which is included in the return value.

That method in turn just returns an RFC 2898 hash, so you could also use System.Security.Cryptography.Rfc2898DeriveBytes, which is what the HashPassword method uses.security.cryptography.rfc2898derivebytes.aspx, but then you need to worry about the salting.

Using the HashPassword method should work perfectly for your security requirement; I use this when I am asked to enforce requirements such as new passwords not matching any of the last 5 (regardless of whether this is a good security requirement or not, it works). You will need the Crypto.VerifyHashedPassword method to see if the password entered matches any of the historic ones, as this will take care of the salt for you as well.