|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Password |
|
5
|
|
|
* |
|
6
|
|
|
* Password hashing. |
|
7
|
|
|
* |
|
8
|
|
|
* @package core |
|
9
|
|
|
* @author [email protected] |
|
10
|
|
|
* @copyright Caffeina srl - 2015 - http://caffeina.it |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
class Password { |
|
14
|
|
|
use Module; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Create a secure password hash. |
|
18
|
|
|
* @param string $password |
|
19
|
|
|
* @return string |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function make($password){ |
|
22
|
|
|
// Pre PHP 5.5 support |
|
23
|
|
|
if (!defined('PASSWORD_DEFAULT')) { |
|
24
|
|
|
return '$5h$'.hash('sha1',$password); |
|
25
|
|
|
} else { |
|
26
|
|
|
return password_hash($password,PASSWORD_BCRYPT,['cost' => 12]); |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Verify if password match a given hash |
|
32
|
|
|
* @param string $password The password to check |
|
33
|
|
|
* @param string $hash The hash to match against |
|
34
|
|
|
* @return bool Returns `true` if hash match password |
|
35
|
|
|
*/ |
|
36
|
|
|
public static function verify($password, $hash){ |
|
37
|
|
|
// Pre PHP 5.5 support |
|
38
|
|
|
if (!defined('PASSWORD_DEFAULT') || substr($hash,0,4)=='$5h$') { |
|
39
|
|
|
return '$5h$'.hash('sha1',$password) == $hash; |
|
40
|
|
|
} else { |
|
41
|
|
|
return password_verify($password,$hash); |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Helper for secure time-constant string comparison |
|
47
|
|
|
* Protect from time-based brute force attacks. |
|
48
|
|
|
* @param string $a First string to compare |
|
49
|
|
|
* @param string $b Second string to compare |
|
50
|
|
|
* @return boll Returns `true` if strings are the same |
|
51
|
|
|
*/ |
|
52
|
|
|
public static function compare($a, $b){ |
|
53
|
|
|
return hash_equals($a, $b); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
// Polyfill hash_equals (PHP < 5.6.0) |
|
60
|
|
|
// http://php.net/manual/en/function.hash-equals.php |
|
61
|
|
|
if(!function_exists('hash_equals')) { |
|
62
|
|
|
function hash_equals($a, $b) { |
|
63
|
|
|
return substr_count("$a" ^ "$b", "\0") * 2 === strlen("$a$b"); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|