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

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

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