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


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