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