Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
BCrypt implementations
/* $2$(2 chars work)$(22 chars salt)(31 chars hash)
* 2 - the original BCrypt, which has been deprecated because of a security issue a long time before BCrypt became popular.
* 2a - the official BCrypt algorithm and a insecure implementation in crypt_blowfish
* 2x - suggested for hashes created by the insecure algorithm for compatibility
* 2y - suggested new marker for the fixed crypt_blowfish
* So 2a hashes created by the original algorithm or the java port are fine, and identical to 2y-hashes created by
* crypt_blowfish. But 2a hashes created by crypt_blowfish are insecure. */
// Java Spring Security 4+
// not interoperable with PHP $2y, just replace it
String password = "plaintextPassword";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
// PHP 5.5+
$hash = password_hash("plaintextPassword", PASSWORD_BCRYPT, array("cost" => 11));
echo $hash;
if(password_verify("plaintextPassword", $hash))
echo "password ok";
echo "password FAIL";
-- PostgreSQL 8.4+
SELECT crypt('plaintextPassword', gen_salt('bf', 11));
-- $2a$10$d6xTF88NYNb8solSKuv8NuFeIFkSNTjz4AVtctw3Z8WCSvpCuTtlS
SELECT crypt('plaintextPassword', '$2a$10$d6xTF88NYNb8solSKuv8NuFeIFkSNTjz4AVtctw3Z8WCSvpCuTtlS') = '$2a$10$d6xTF88NYNb8solSKuv8NuFeIFkSNTjz4AVtctw3Z8WCSvpCuTtlS'
# Python
# pip install bcrypt
import bcrypt
# gensalt's log_rounds parameter determines the complexity.
# The work factor is 2**log_rounds, and the default is 12
hashed = bcrypt.hashpw(password, bcrypt.gensalt(10));
# Check that an unencrypted password matches one that has
# previously been hashed
if bcrypt.hashpw(password, hashed) == hashed:
print "It matches"
print "It does not match"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.