Created
April 22, 2012 15:37
-
-
Save mcdado/2464692 to your computer and use it in GitHub Desktop.
PHP Bcrypt class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
bcrypt class for PHP 5.3 and above. | |
An implentation by Marco Arment. | |
It uses Blowfish hashing. | |
Simplified by David Gasperoni <[email protected]>. | |
Forked from Marco Arment <[email protected]>. | |
This code is released in the public domain. | |
THERE IS ABSOLUTELY NO WARRANTY. | |
Usage example: | |
// In a registration or password-change form: | |
$hash_for_user = Bcrypt::hash($_POST['password']); | |
// In a login form: | |
$is_correct = Bcrypt::check($_POST['password'], $stored_hash_for_user); | |
*/ | |
class Bcrypt | |
{ | |
const DEFAULT_WORK_FACTOR = 8; | |
public static function hash($password, $work_factor = 0) | |
{ | |
if ( version_compare(PHP_VERSION, '5.3') < 0 ) { | |
throw new Exception('Bcrypt requires PHP 5.3 or above'); | |
} | |
if ( ! function_exists('openssl_random_pseudo_bytes') ) { | |
throw new Exception('Bcrypt requires openssl PHP extension'); | |
} | |
if ( $work_factor < 4 || $work_factor > 31 ) | |
$work_factor = self::DEFAULT_WORK_FACTOR; | |
$salt = '$2a$' . | |
str_pad($work_factor, 2, '0', STR_PAD_LEFT) . '$' . | |
substr( | |
strtr(base64_encode(openssl_random_pseudo_bytes(16)), '+', '.'), | |
0, | |
22 | |
) | |
; | |
return crypt($password, $salt); | |
} | |
public static function check($password, $stored_hash) | |
{ | |
if ( version_compare(PHP_VERSION, '5.3') < 0 ) { | |
throw new Exception('Bcrypt requires PHP 5.3 or above'); | |
} | |
return crypt($password, $stored_hash) == $stored_hash; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment