How to Create a Password Hash in PHP
As more secure web services avoid storing passwords in plain text format, languages such as PHP provide various (undecryptable) hash functions to support the more secure industry standard. This tutorial provides explaining how to create proper hashing in PHP.
Creating a password hash
Create password hashes using
password_hash() to use the current industry best-practice standard hash or key derivation. At time of writing, the standard is bcrypt, which means, that
PASSWORD_DEFAULT contains the same value as
$options = [ 'cost' => 12, ]; $hashedPassword = password_hash($plaintextPassword, PASSWORD_DEFAULT, $options);
The third parameter is not mandatory.
'cost' value should be chosen based on your production server's hardware. Increasing it will make the password more costly to generate. The costlier it is to generate the longer it will take anyone trying to crack it to generate it also. The cost should ideally be as high as possible, but in practice, it should be set so it does not slow down everything too much. Somewhere between 0.1 and 0.4 seconds would be okay. Use the default value if you are in doubt.
Salt for password hash
Despite the reliability of crypt algorithm, there is still vulnerability against rainbow tables. That's the reason, why it's recommended to use salt.
A salt is something that is appended to the password before hashing to make source string unique. Given two identical passwords, the resulting hashes will be also unique, because their salts are unique.
A random salt is one of the most important pieces of your password security. This means that even with a lookup table of known password hashes an attacker can’t match up your user’s password hash with the database password hashes since a random salt has been used. You should use always random and cryptographically secure salts.
bcrypt algorithm, plain text salt is stored along with the resulting hash, which means that the hash can be transferred across different systems and platforms and still be matched against the original password.
Even when this is discouraged, you can use the salt option to define your own random salt.
$options = [ 'salt' => $salt, //see example below ];
If you omit this option, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.
The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.