Created
August 8, 2017 03:58
-
-
Save ryankshah/b0b78eb6e9d3df5b69c9b0fe8a755d1c to your computer and use it in GitHub Desktop.
BCrypt Hashing And Validation Functions in PHP for Passwords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 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) { | |
if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) { | |
/** | |
* 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