Simple BCrypt Implementation



Published: 2017-05-14 13:05:59 +0000
Categories: PHP,

Language

PHP

Description

A simple implementation of the Blowfish Crypt (BCrypt) password storage mechanism in PHP.

PHP 5.5.0 onwards makes this available via the password_hash function, so this should only be used to implement support in versions prior to that

Similar to

Snippet

function bCrypt($pass,$cost){
      $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

      // Build the beginning of the salt
      $salt=sprintf('$2a$%02d$',$cost);

      // Seed the random generator
      mt_srand();

      // Generate a random salt
      for($i=0;$i<22;$i++) $salt.=$chars[mt_srand(0,63)];

     // return the hash
    return crypt($pass,$salt);
}

Usage Example

// Set the password in a variable
$pass = 'Password';
$hash = bCrypt($pass,12);

// We've now got the hash and can store it in a db, or in a file.

// To check the password
if ($hash == crypt($pass,$hash)){
    echo "Logged in";
}else{
    echo "access denied"
}

License

BSD-3-Clause

Keywords

password, hashing, storage, bcrypt, implementation, example, blowfish,

Latest Posts

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

Copyright © 2018 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion