Show How to increase hash securityThe hash generated by password_hash() is very secure. But you can make it even stronger with two simple techniques:
Bcrypt costBcrypt is the current default hashing algorithm used by password_hash(). This algorithm takes an option parameter named “cost”. The default cost value is 10. By increasing the cost, you can make the hash more difficult to compute. The higher the cost, the longer the time needed to create the hash. A higher cost makes more difficult to break the hash. However, it also makes the hash creation and check longer, too. So, you want to find a compromise between security and server load. This is how you can set a custom cost value for password_hash():
But what cost value should you set? A good compromise is a cost value that lets your server create the hash in about 100ms. Here is a simple test to find this value:
Once you have found your cost, you can use it every time you execute password_hash() like in the previous example. Keeping your hashes up to date with password_needs_rehash()To understand this step, let’s see how password_hash() works. password_hash() takes three arguments:
PHP supports different hashing algorithms, but you usually want to use the default one. You can select the default algorithm by using the PASSWORD_DEFAULT constant, as you have seen in the previous examples. As of June 2020, the default algorithm is Bcrypt. However, PHP can change the default algorithm in the future, if a better and more secure algorithm is implemented. When that happens, the PASSWORD_DEFAULT constant will point to the new algorithm. So, all the new hashes will be created using the new algorithm. But what if you want to take all your old hashes, made with the previous algorithm, and automatically create them again with the new one? This is where password_needs_rehash() comes into play. This function checks if a hash has been created with a given algorithm and parameters. For example:
If the current default hashing algorithm is different from the algorithm used to create the hash, password_needs_rehash() returns true. password_needs_rehash() also checks if the options parameter is different. This is very handy if you want to update your hashes after you change a parameter like the Bcrypt cost. This example shows how you can automatically check a password hash and update it if needed, when a remote user logs in: |