Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
How to use bcrypt in PHP to safely store passwords (PHP 5.3+ only)
// secure hashing of passwords using bcrypt, needs PHP 5.3+
// see
// salt for bcrypt needs to be 22 base64 characters (but just [./0-9A-Za-z]), see
// just an example; please use something more secure/random than sha1(microtime) :)
$salt = substr(str_replace('+', '.', base64_encode(sha1(microtime(true), true))), 0, 22);
// 2a is the bcrypt algorithm selector, see
// 12 is the workload factor (around 300ms on my Core i7 machine), see
$hash = crypt('foo', '$2a$12$' . $salt);
// we can now use the generated hash as the argument to crypt(), since it too will contain $a2$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
Something went wrong with that request. Please try again.