-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPassword.php
113 lines (95 loc) · 2.51 KB
/
Password.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Depage\Auth;
class Password
{
/**
* @brief realm
**/
protected $realm = null;
public function __construct($realm, $digestCompat = false)
{
if (!function_exists("password_hash")) {
require_once(__DIR__ . "/Compat/password.php");
}
$this->realm = $realm;
$this->digestCompat = $digestCompat;
}
// {{{ hash()
/**
* @brief hash
*
* @param mixed $username
* @param mixed $password
* @return string hash
**/
public function hash($username, $password)
{
if ($this->digestCompat) {
return md5($username . ':' . $this->realm . ':' . $password);
} else {
return password_hash($password, \PASSWORD_DEFAULT);
}
}
// }}}
// {{{ needsRehash()
/**
* @brief needsRehash
*
* @param mixed $hash
* @return bool
**/
public function needsRehash($hash)
{
$info = $this->getInfo($hash);
if ($info['algoName'] == "dp-digest" && $this->digestCompat) {
return false;
} else {
return password_needs_rehash($hash, \PASSWORD_DEFAULT);
}
}
// }}}
// {{{ verify()
/**
* @brief verify
*
* @param mixed $username
* @param mixed $password
* @param mixed $hash
* @return bool
**/
public function verify($username, $password, $hash)
{
$info = $this->getInfo($hash);
if ($info['algoName'] == "dp-digest") {
return md5($username . ':' . $this->realm . ':' . $password) == $hash;
} else {
return password_verify($password, $hash);
}
}
// }}}
public function getInfo($hash)
{
$info = password_get_info($hash);
if ($info['algo'] === 0) {
if (strlen($hash) == 32) {
// assume digest md5 hash based on hash length
$info['algoName'] = "dp-digest";
}
}
return $info;
}
public function generate($options = array())
{
$options = array_merge(array(
'length' => 8,
), $options);
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$count = mb_strlen($chars);
for ($i = 0, $result = ''; $i < $options['length']; $i++) {
$index = mt_rand(0, $count - 1);
$result .= mb_substr($chars, $index, 1);
}
return $result;
}
}
/* vim:set ft=php sw=4 sts=4 fdm=marker : */