I am thinking of using password_hash() function to encrypt user passwords. I understand that this function generates salt by default if you don't provide it, and it is even encouraged to use the default salt instead of your own. I am currently weighing in 3 options and can't decide which one to go with so I'd appreciate it if you could help me out.
1. option: password_hash() with default salt
$passwordInput = $_POST['password'];
$passwordHash = password_hash($passwordInput, PASSWORD_BCRYPT);
//INSERT $passwordHash INTO DATABASE
2. option: password_hash() with custom salt
$options = ['salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$passwordInput = $_POST['password'];
$passwordHash = password_hash($passwordInput, PASSWORD_BCRYPT, $options);
//INSERT $passwordHash INTO DATABASE
3. option: not using password_hash() at all
I am basing this option on a post from 2014: The definitive guide to form-based website authentication. Basically if it is a more secure approach than password_hash() I'd use something like this:
$salt = uniqid(rand(0, 1000000);
$passwordInput = $_POST['password'];
$password = hash('sha512', $salt . $passwordInput);
//INSERT $password AND $salt INTO DATABASE SEPARATELY
It is a one-way algorithm, in that you don't decrypt it to validate it, you simply pass the original string in with your password and if it generates the same hash for the provided password, you're authenticated. It's best to omit the salt and let it generate one for you.
password_hash() creates a new password hash using a strong one-way hashing algorithm. The following algorithms are currently supported: PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5. 0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
You can't decrypt it. A hash is a one-way function. Hash the password the user has given you and see the the hashes match.
A cryptographic salt is made up of random bits added to each password instance before its hashing. Salts create unique passwords even in the instance of two users choosing the same passwords. Salts help us mitigate hash table attacks by forcing attackers to re-compute them using the salts for each user.
The really short answer to this question is to use password_hash()
with the default salt (your first option), custom salt is deprecated in PHP7 because, to quote php.net:
The salt option for the password_hash() function has been deprecated to prevent developers from generating their own (usually insecure) salts. The function itself generates a cryptographically secure salt when no salt is provided by the developer - therefore custom salt generation should not be needed.
By the same token, your third option, hash()
should be avoided as again you'll need to generate your own salt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With