1
|
|
|
<?php |
2
|
|
|
namespace Bcrypt; |
3
|
|
|
|
4
|
|
|
class Bcrypt |
5
|
|
|
{ |
6
|
|
|
const VERSION = '1.0.0'; |
7
|
|
|
|
8
|
|
|
public static function encrypt($plaintext, $bcrypt_version="2y", $cost=10) |
|
|
|
|
9
|
|
|
{ |
10
|
|
|
//make sure adding the cost in two digits |
11
|
|
|
$cost = sprintf('%02d', $cost); |
12
|
|
|
|
13
|
|
|
$salt=self::generateSalt(); |
14
|
|
|
|
15
|
|
|
/* Create a string that will be passed to crypt, containing all |
16
|
|
|
* of the settings, separated by dollar signs |
17
|
|
|
*/ |
18
|
|
|
$salt='$'.implode('$',[$bcrypt_version, $cost, $salt]); |
19
|
|
|
|
20
|
|
|
$ciphertext = crypt($plaintext, $salt); |
21
|
|
|
|
22
|
|
|
return $ciphertext; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public static function verify($plaintext, $ciphertext) |
|
|
|
|
26
|
|
|
{ |
27
|
|
|
if(version_compare(PHP_VERSION, '5.6.0', '>=')){ |
28
|
|
|
return hash_equals($ciphertext, crypt($plaintext, $ciphertext)); |
29
|
|
|
} |
30
|
|
|
return crypt($plaintext, $ciphertext) == $ciphertext; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public static function generateSalt(){ |
34
|
|
|
/* To generate the salt, first generate enough random bytes. Because |
35
|
|
|
* base64 returns one character for each 6 bits, the we should generate |
36
|
|
|
* at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first |
37
|
|
|
* 22 base64 characters |
38
|
|
|
*/ |
39
|
|
|
$bytes = openssl_random_pseudo_bytes(17); |
40
|
|
|
|
41
|
|
|
if($bytes === false){ |
42
|
|
|
throw new RuntimeException('Unable to generate a random string'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$salt = substr(base64_encode($bytes),0,22); |
46
|
|
|
|
47
|
|
|
/* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to |
48
|
|
|
* replace any '+' in the base64 string with '.'. We don't have to do |
49
|
|
|
* anything about the '=', as this only occurs when the b64 string is |
50
|
|
|
* padded, which is always after the first 22 characters. |
51
|
|
|
*/ |
52
|
|
|
$salt=str_replace("+",".",$salt); |
|
|
|
|
53
|
|
|
return $salt; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
PHP provides two ways to mark string literals. Either with single quotes
'literal'
or with double quotes"literal"
. The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (
\'
) and the backslash (\\
). Every other character is displayed as is.Double quoted string literals may contain other variables or more complex escape sequences.
will print an indented:
Single is Value
If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.
For more information on PHP string literals and available escape sequences see the PHP core documentation.