Last active

Embed URL


SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

How to use bcrypt in PHP to safely store passwords (PHP 5.3+ only)

View bcrypt.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 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
$salt = substr(strtr(base64_encode(openssl_random_pseudo_bytes(22)), '+', '.'), 0, 22);
// 2y is the bcrypt algorithm selector, see
// 12 is the workload factor (around 300ms on my Core i7 machine), see
$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
grugnog commented

See for examples of good random sources and base64 generation.

something more random than base64_encode(sha1(microtime(true), true))), 0, 22) would be:
Instead bin2hex(openssl_random_pseudo_bytes(22));
openssl_random_pseudo_bytes is the most secure prng available in most php distributions

So this is all you need? :) Great!

$blowfish_salt = bin2hex(openssl_random_pseudo_bytes(22));
$hash = crypt($_POST['password'], "$2a$12$".$blowfish_salt);
// Save the hash but no need to save the salt

if (crypt($_POST['password'], $hash) == $hash) {
    // Verified

Seems like you do need to save the salt. I can't get the two hashes to match otherwise. Would you recommend having a static salt instead of setting it dynamically and storing it in the database? That way, even if the database was compromised, the hacker would not be able to read the hashes without the salt which is inside your code.

@ nagarjun, the point of bcrypt and using blowfish ($2a$) is that you set a work factor high enough where it would take someone a very long time to crack a single password even though they have the salt and the final hash right there.

A single static salt that all users would share makes the whole storage mechanism less secure. A random salt per user, with a high enough work factor, is all you need.

FYI use PHP's built in bcrypt and don't save the salt, but do increase the complexity integer as time goes on, security has never been so syntactically sugary. The function:

@charleshross What if you don't have PHP 5.5 installed?

@bruce-lim Use the password_compat library:

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.