Using bcrypt in CakePHP 2.3

CakePHP 2.3 adds native support for the bcrypt hashing algorithm, which is often recommended because of the amount of analysis that’s gone into it and its configurable cost function.

Using it isn’t obvious, however. The 2.3 migration notes merely say, You can now use Blowfish in your $authenticate array to allow bcrypt passwords to be used.

Due to limitations in how Auth works, a new authentication type was added in addition to a new hash type. So to use bcrypt, your $authenticate variable should look like this:

[php]
$this->Auth->authenticate = array(
AuthComponent::ALL => array(
‘scope’ => array(‘User.active’ => 0)
),
‘Blowfish’,
);
[/php]

That only affects checking the password. To hash passwords using bcrypt, you also need to modify your model because Auth::password won’t work.

[php]
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias][‘password’])) {
$this->data[$this->alias][‘password’] =
Security::hash($this->data[$this->alias][‘password’], "blowfish");
}
return true;
}
[/php]

Note that you can configure the cost by using Security::setCost (the default is 10).

Leave a Reply