|
1
|
|
|
<?php |
|
2
|
|
|
namespace Bcrypt; |
|
3
|
|
|
|
|
4
|
|
|
class Bcrypt |
|
5
|
|
|
{ |
|
6
|
|
|
const VERSION = '1.0.0'; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* @return string The encrypt text |
|
10
|
|
|
*/ |
|
11
|
|
|
public static function encrypt($plaintext, $bcrypt_version = '2y', $cost = 10) |
|
12
|
|
|
{ |
|
13
|
|
|
//make sure adding the cost in two digits |
|
14
|
|
|
$cost = sprintf('%02d', $cost); |
|
15
|
|
|
|
|
16
|
|
|
$salt = self::generateSalt(); |
|
17
|
|
|
|
|
18
|
|
|
/* Create a string that will be passed to crypt, containing all |
|
19
|
|
|
* of the settings, separated by dollar signs |
|
20
|
|
|
*/ |
|
21
|
|
|
$salt = '$'.implode('$', [$bcrypt_version, $cost, $salt]); |
|
22
|
|
|
|
|
23
|
|
|
$ciphertext = crypt($plaintext, $salt); |
|
24
|
|
|
|
|
25
|
|
|
return $ciphertext; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @return boolean The result that plaintext equals ciphertext or not |
|
30
|
|
|
*/ |
|
31
|
|
|
public static function verify($plaintext, $ciphertext) |
|
32
|
|
|
{ |
|
33
|
|
|
if (version_compare(PHP_VERSION, '5.6.0', '>=')) { |
|
34
|
|
|
return hash_equals($ciphertext, crypt($plaintext, $ciphertext)); |
|
35
|
|
|
} |
|
36
|
|
|
return crypt($plaintext, $ciphertext) == $ciphertext; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public static function generateSalt() |
|
40
|
|
|
{ |
|
41
|
|
|
/* To generate the salt, first generate enough random bytes. Because |
|
42
|
|
|
* base64 returns one character for each 6 bits, the we should generate |
|
43
|
|
|
* at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first |
|
44
|
|
|
* 22 base64 characters |
|
45
|
|
|
*/ |
|
46
|
|
|
$bytes = openssl_random_pseudo_bytes(17); |
|
47
|
|
|
|
|
48
|
|
|
if ($bytes === false) { |
|
49
|
|
|
throw new RuntimeException('Unable to generate a random string'); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$salt = substr(base64_encode($bytes), 0, 22); |
|
53
|
|
|
|
|
54
|
|
|
/* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to |
|
55
|
|
|
* replace any '+' in the base64 string with '.'. We don't have to do |
|
56
|
|
|
* anything about the '=', as this only occurs when the b64 string is |
|
57
|
|
|
* padded, which is always after the first 22 characters. |
|
58
|
|
|
*/ |
|
59
|
|
|
$salt = str_replace('+', '.', $salt); |
|
60
|
|
|
return $salt; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|