|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ffcms\Core\Helper; |
|
4
|
|
|
|
|
5
|
|
|
use Ffcms\Core\Helper\Type\Str; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class Crypt. All cryptography features simplification for ffcms |
|
9
|
|
|
* @package Ffcms\Core\Helper |
|
10
|
|
|
*/ |
|
11
|
|
|
class Crypt |
|
12
|
|
|
{ |
|
13
|
|
|
const PASSWORD_CRYPT_ALGO = PASSWORD_BCRYPT; |
|
14
|
|
|
const PASSWORD_CRYPT_COST = 12; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Generate password hash using php password_hash with predefined algo |
|
18
|
|
|
* @param string $text |
|
19
|
|
|
* @return null|string |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function passwordHash(string $text): ?string |
|
22
|
|
|
{ |
|
23
|
|
|
return password_hash($text, self::PASSWORD_CRYPT_ALGO, [ |
|
24
|
|
|
'cost' => self::PASSWORD_CRYPT_COST |
|
25
|
|
|
]); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Verify password to hash equality |
|
30
|
|
|
* @param string $password |
|
31
|
|
|
* @param string $hash |
|
32
|
|
|
* @return bool |
|
33
|
|
|
*/ |
|
34
|
|
|
public static function passwordVerify(string $password, string $hash): bool |
|
35
|
|
|
{ |
|
36
|
|
|
return (Str::length($hash) > 0 && password_verify($password, $hash)); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Check if password encryption is from old ffcms version (3.0 blowfish with cost=7 and predefined salt) |
|
41
|
|
|
* @param string $hash |
|
42
|
|
|
* @return bool |
|
43
|
|
|
*/ |
|
44
|
|
|
public static function isOldPasswordHash(string $hash): bool |
|
45
|
|
|
{ |
|
46
|
|
|
return Str::startsWith('$2a$07$', $hash); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Generate random string with numbers from secure function random_bytes |
|
51
|
|
|
* @param int $length |
|
52
|
|
|
* @return string |
|
53
|
|
|
*/ |
|
54
|
|
|
public static function randomString(int $length): string |
|
55
|
|
|
{ |
|
56
|
|
|
try { |
|
57
|
|
|
$rand = bin2hex(random_bytes($length)); |
|
58
|
|
|
// bytes_length = length * 2 |
|
59
|
|
|
$rand = substr($rand, 0, $length); |
|
60
|
|
|
} catch (\Exception $ce) { |
|
61
|
|
|
$rand = Str::randomLatinNumeric($length); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return $rand; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|