Menu Get a free quote


A PHP class to hash passwords using bcrypt

Change lab project:


A PHP class to hash passwords using bcrypt.


For information on what password hashing is please read “About Secure Password Hashing” from the StackExchange blog

This class uses the PHP implementation of bcrypt, a key derivation function for passwords based on the Blowfish cipher.

bcrypt is an excellent choice for password hashing because it is slow, making the production of rainbow tables time-consuming, and it forces you to use a salt — which is stored along with the hash.

Unless you’re a security expert you really shouldn’t be writing your own hashing functions so it is best to use PHP’s native functions.

PHP has a crypt() function that supports several different hashing algorithms, including Blowfish. While using bcrypt isn’t all that difficult it can be used incorrectly. This class aims to make it easy to securely hash your password by:

  1. Checking if Blowfish is installed and throwing an exception if it isn’t
  2. Allowing you to set the number of rounds; more rounds = slower but more secure
  3. Creating a salt automatically (Blowfish only allows a 22 character string for its salt only counting characters./0-9A-Za-z)
  4. Setting the salt prefix automatically based on the PHP version; salt prefix is any of the following: $2a$, $2x$ or $2y$ (see note below*)


 * Include the class
require 'BcryptHasher.php';

 * - Create a BcryptHasher.php object
 * - You can optionally set the number of rounds here
 * - Rounds can be between 4 and 31
 * - More rounds is slower and more secure
 * - The default is 9
 * - You can change the rounds using $bcryptHasher->setRounds($rounds);
try {

    $bcryptHasher = new BcryptHasher();
catch(Exception $e) {

    // Blowfish isn't installed, check your hosting setup
    // Any decent hosting company should have this installed


 * Variables to test
$passwordToHash         = 'testP@$$w0rd';
$incorrectPassword      = 'Wrong password!';

 * Hash the password
$hashedPassword = $bcryptHasher->hash($passwordToHash);

 * Here's the hashed password; Blowfish stores the salt and the hash together
echo '<p>Hashed password: ' . $hashedPassword . '</p>';

 * Hashing is a one-way process so to check if a password is correct we hash the 
 * one inputted by a user (e.g. from a login page) and compare the hashed results
echo '<pre>';
var_dump($bcryptHasher->compare($passwordToHash,    $hashedPassword)); // True, correct password
var_dump($bcryptHasher->compare($incorrectPassword, $hashedPassword)); // False, incorrect password
echo '</pre>';

*Note about the salt prefix

Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use “$2y$” in preference to “$2a$”.




Function Arguments Description
setRounds rounds (int) Sets the number of rounds


1.0.1 — 10 April 2015
Readme and license updated

First version


Open source under the MIT license.