Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
BCrypt Hashing And Validation Functions in PHP for Passwords
* Generate a secure BCrypt hash for a given password.\n
* The cost is passed to the blowfish algorithm provided
* by PHP.
function generateBCryptHash($password, $cost) {
* To generate the salt, we first follow the requirement
* that the salt starts with '$2a$' or '$2y$'.\n
* This is then followed by a two digit number in the range
* from 4 to 31. This will be the cost that makes brute
* force attacks take longer.\n
* Lastly, we append 22 alphanumeric characters completing
* the main part of our salt.
$salt = '$2y$'.$cost.'$'.substr(md5(uniqid(rand(), true)), 0, 22);
return crypt($password, $salt);
* Verify a secure BCrypt hash by comparing a stored hash
* with one that will be generated using the raw input.
function verifyBCryptHash($password, $passwordHash) {
return crypt($password, $passwordHash) == $passwordHash;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment