How to automatically generate salt for crypt method with blowfish

Connel picture Connel · Nov 26, 2012 · Viewed 8.5k times · Source

I have just started learning PHP and I want to create a website with a login for my final year university project. I've read that blowfish is the best method for hashing in a number of places like here: openssl_digest vs hash vs hash_hmac? Difference between SALT & HMAC?

Everywhere I read about the crypt method includes a string like $2y$07$usesomesillystringforsalt$ My main question is: how do I randomly generate this? I've read in places that time stamps and mt_rand() are not secure.

Also I've heard AES is the preferred technology recently but from what I can see it seems pretty tricky to implement in PHP! Is blowfish still an acceptable method to secure stored passwords?

Answer

martinstoeckli picture martinstoeckli · Nov 26, 2012

A salt should be unique (for each password) and unpredictable. These two criterias are a bit difficult to fulfill with a deterministic computer, so the best thing you can do is, to use the random source of the operating system, to generate the salt.

Time stamps, as well as the mt_rand() function, are not ideal, because one can argue that they are predictable. At least an attacker can narrow down (and therefore precalculate) the possible combinations for a certain period. While this may not have a big impact in practice, why not do the best you can?

Since PHP 5.3 you can safely use the mcrypt_create_iv() function to read from the random source, then you will have to encode the binary string to the allowed alphabet. This is a possible implementation.

PHP 5.5 will have it's own functions password_hash() and password_verify() ready, to simplify this task. There is also a compatibility pack for PHP 5.3/5.4 available, downloadable at password_compat.