forked from cosenary/Bcrypt-PHP-Class
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bcrypt.php
117 lines (99 loc) · 2.46 KB
/
Bcrypt.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* Bcrypt class
*
* @author Christian Metz
* @since 23.06.2012
* @copyright Christian Metz - MetzWeb Networks 2012
* @version 1.0
* @license BSD http://www.opensource.org/licenses/bsd-license.php
*/
class Bcrypt {
/**
* Work cost factor
* range between [04; 31]
*
* @var string
*/
private static $_workFactor = 12;
/**
* Default identifier
*
* @var string
*/
private static $_identifier = '2y';
/**
* All valid hash identifiers
*
* @var array
*/
private static $_validIdentifiers = array ('2a', '2x', '2y');
/**
* Hash password
*
* @param string $password
* @param integer [optional] $workFactor
* @return string
*/
public static function hashPassword($password, $workFactor = 0) {
if (version_compare(PHP_VERSION, '5.3') < 0) {
throw new Exception('Bcrypt requires PHP 5.3 or above');
}
$salt = self::_genSalt($workFactor);
return crypt($password, $salt);
}
/**
* Check bcrypt password
*
* @param string $password
* @param string $storedHash
* @return boolean
*/
public static function checkPassword($password, $storedHash) {
if (version_compare(PHP_VERSION, '5.3') < 0) {
throw new Exception('Bcrypt requires PHP 5.3 or above');
}
self::_validateIdentifier($storedHash);
$checkHash = crypt($password, $storedHash);
return ($checkHash === $storedHash);
}
/**
* Generates the salt string
*
* @param integer $workFactor
* @return string
*/
private static function _genSalt($workFactor) {
if ($workFactor < 4 || $workFactor > 31) {
$workFactor = self::$_workFactor;
}
$input = self::_getRandomBytes();
$salt = '$' . self::$_identifier . '$';
$salt .= str_pad($workFactor, 2, '0', STR_PAD_LEFT);
$salt .= '$';
$salt .= substr(strtr(base64_encode($input), '+', '.'), 0, 22);
return $salt;
}
/**
* OpenSSL's random generator
*
* @return string
*/
private static function _getRandomBytes() {
if (!function_exists('openssl_random_pseudo_bytes')) {
throw new Exception('Unsupported hash format.');
}
return openssl_random_pseudo_bytes(16);
}
/**
* Validate identifier
*
* @param string $hash
* @return void
*/
private static function _validateIdentifier($hash) {
if (!in_array(substr($hash, 1, 2), self::$_validIdentifiers)) {
throw new Exception('Unsupported hash format.');
}
}
}