Cakephp 3.0 alpha2 How to compare new password to

2019-09-06 00:51发布

问题:

Okay, so I am testing out Cakephp 3.0 alpha2 by transferring my application(2.5) to 3.x. My current application has it set up so that when you reset your password you cannot change it to any of the previous six passwords(stored in a passwords table that connects it by the user_id) for security purposes. As I look at the changes in Cake 3.0, I noticed that if you create a new entity that the password hashes differently even if it is the same password. What would be a good way to compare the new password to the old ones? Would I go about using the password hasher built in function called check?

回答1:

CakePHP 3 uses bcrypt. In brief: bcrypt uses a different salt for each password, and stores the salt as part of the password hash. That is why, as you've found, bcrypt will generate a different hash each time the same plain-text password is encrypted.

However, if it's to be of any use as an authentication system, you have to be able to check if a plain-text password 'fits' for a given hashed version of that password - even though there's not one single 'correct' hashed version, right? Right.

You do this with the password_verify method - http://au2.php.net/password_verify

So, rather than hashing the plain-text version and seeing if the hashed version of the new password matches the hashed versions of each of the past 6 versions, you have to call password_verify on the plain-text password 6 times - once for each of the previous hashed passwords, to see if there are any matches.

There's a good explanation of bcrypt in php here: How do you use bcrypt for hashing passwords in PHP? I'd recommend reading that - once you understand how bcrypt treats passwords, your problem shouldn't be too hard to solve.