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:

$this->Auth->authenticate = array(
            AuthComponent::ALL => array(
                'scope' => array('' => 0)

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

    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;

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

Googling for bugs: hundreds of date-formatting mistakes

Here’s something really easy to screw up:

echo date("Y-m-d H:m:s");

Spot the mistake? The “m” format code can only mean one thing, which is “months”, not “minutes”. Yet, when you’re writing code in a hurry, it’s so easy to quickly write this code and assume it works. After all, it raises no errors or warnings, and always generates valid datetime strings. It’s just wrong.

Googling for ‘ “Y-m-d H:m:s” php’ returns hundreds of examples of mistakes. I tried to fix a couple instances but realized that there’s so much abandoned code on Github that it would’ve been useless.

This is a prime example of something that static analysis could warn about: just look for “H:m:s” or “h:m:s” in the first argument to date. This mistake isn’t limited to PHP, of course, as this Java example shows.