Last active
March 28, 2023 13:15
-
-
Save dzuelke/972386 to your computer and use it in GitHub Desktop.
How to use bcrypt in PHP to safely store passwords (PHP 5.3+ only)
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 | |
// secure hashing of passwords using bcrypt, needs PHP 5.3+ | |
// see http://codahale.com/how-to-safely-store-a-password/ | |
// salt for bcrypt needs to be 22 base64 characters (but just [./0-9A-Za-z]), see http://php.net/crypt | |
$salt = substr(strtr(base64_encode(openssl_random_pseudo_bytes(22)), '+', '.'), 0, 22); | |
// 2y is the bcrypt algorithm selector, see http://php.net/crypt | |
// 12 is the workload factor (around 300ms on my Core i7 machine), see http://php.net/crypt | |
$hash = crypt('foo', '$2y$12$' . $salt); | |
// we can now use the generated hash as the argument to crypt(), since it too will contain $2y$12$... with a variation of the hash. No need to store the salt anymore, just the hash is enough! | |
var_dump($hash == crypt('foo', $hash)); // true | |
var_dump($hash == crypt('bar', $hash)); // false | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please, read this, is very important to understand about secure and insecure salt techniques: https://crackstation.net/hashing-security.htm#phpsourcecode
Here, as you can see, PHP 5.5 has implemented the PBKDF2 noticed by Crackstation:
http://php.net/manual/pt_BR/function.hash-pbkdf2.php.
If you are using PHP 5.5+ use @charleshross tip.
From manuals (http://php.net/password_hash):
"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."
It because,
password_hash()
withPASSWORD_DEFAULT
uses strong techniques to generate the salt behind the scenes.Regards.