Blowfish-based hashing for passwords in PHP

Storing passwords in a secure manner is very essential. Users can fall victim of cybercrime if a system containing the passwords of the users has been breached. DataLossDB illustrates the amount of data lost due to breaches.

A cryptographic hash function can be used for creating a representation of a plaintext password, also known as a hash. The hash cannot be reversed to reveal the password, it has been generated with a one-way process.

The example below uses a secure Blowfish-based hashing algorithm to hash a password. A so called salt is required for hashing, in this case it’s a random string consisting of 20 upper case and lower case characters. The plaintext password entered by the user and the salt can be used to regenerate the hash and compare it with the stored hash for verifying the password.


// Generate a salt with a length of 20 characters
$salt = generateSalt(20);

// Plaintext password
$password = 'foo bar';

// Required for CRYPT_BLOWFISH
$salt = '$2a$07$'.$salt.'$';

echo 'Plaintext password: '.$password."\n";
echo 'Salt: '.$salt."\n";

// Hash the password and print the results
echo 'Blowfish hash: ' . crypt($password, $salt)."\n";

function generateSalt($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $salt = '';

    for ($i=0;$i<$length;$i++) {
        $salt .= $chars[mt_rand(0, strlen($chars)-1)];

    return $salt;



Plaintext password: foo bar
Salt: $2a$07$PjkIDpXPETirGgMElYSu$
Blowfish hash: $2a$07$PjkIDpXPETirGgMElYSu$.qZEwEZqkH2X8Q776TvtJy4KodHj7gZS
This entry was posted in PHP and tagged , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. ElFeliz
    Posted October 12, 2012 at 6:51 pm | Permalink

    Must be

    $salt .= $chars[mt_rand(0, strlen($chars)-1)];

    otherwise sometimes generate a string shorter then $length

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?