1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Work with one-way encryption |
5
|
|
|
* |
6
|
|
|
* PHP Version 5 |
7
|
|
|
* |
8
|
|
|
* @category Core |
9
|
|
|
* @package Authentication |
10
|
|
|
* @author Hans-Joachim Piepereit <[email protected]> |
11
|
|
|
* @copyright 2013 cSphere Team |
12
|
|
|
* @license http://opensource.org/licenses/bsd-license Simplified BSD License |
13
|
|
|
* @link http://www.csphere.eu |
14
|
|
|
**/ |
15
|
|
|
|
16
|
|
|
namespace csphere\core\authentication; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Work with one-way encryption |
20
|
|
|
* |
21
|
|
|
* @category Core |
22
|
|
|
* @package Authentication |
23
|
|
|
* @author Hans-Joachim Piepereit <[email protected]> |
24
|
|
|
* @copyright 2013 cSphere Team |
25
|
|
|
* @license http://opensource.org/licenses/bsd-license Simplified BSD License |
26
|
|
|
* @link http://www.csphere.eu |
27
|
|
|
**/ |
28
|
|
|
|
29
|
|
|
abstract class Password |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* Hash a string with an algorithm |
33
|
|
|
* |
34
|
|
|
* @param string $string Raw string |
35
|
|
|
* @param integer $cost Cost between 4 and 31, higher = better but slower |
36
|
|
|
* |
37
|
|
|
* @return string |
38
|
|
|
**/ |
|
|
|
|
39
|
|
|
|
40
|
|
|
public static function hash($string, $cost = 10) |
41
|
|
|
{ |
42
|
|
|
// Check if cost is within limits |
43
|
|
|
if ($cost < 4 || $cost > 31) { |
44
|
|
|
|
45
|
|
|
$cost = 10; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
// Create salt string for crypt function |
49
|
|
|
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM); |
50
|
|
|
$salt = base64_encode($salt); |
51
|
|
|
$salt = str_replace('+', '.', $salt); |
52
|
|
|
|
53
|
|
|
// Set hash type (blowfish) and cost |
54
|
|
|
$salt = '$2y$' . $cost . '$' . $salt . '$'; |
55
|
|
|
|
56
|
|
|
// Get hashed string |
57
|
|
|
$hash = crypt($string, $salt); |
58
|
|
|
|
59
|
|
|
return $hash; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Compare a string with a given password |
64
|
|
|
* |
65
|
|
|
* @param string $string Raw string |
66
|
|
|
* @param string $hash Hashed password to compare with |
67
|
|
|
* |
68
|
|
|
* @return boolean |
69
|
|
|
**/ |
|
|
|
|
70
|
|
|
|
71
|
|
|
public static function compare($string, $hash) |
72
|
|
|
{ |
73
|
|
|
// Use hash as salt since crypt is a one-way algorithm |
74
|
|
|
$verify = crypt($string, $hash); |
75
|
|
|
|
76
|
|
|
// Variable verify should contain the hash |
77
|
|
|
$result = ($verify == $hash) ? true : false; |
78
|
|
|
|
79
|
|
|
return $result; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|