PassHash.php
3.03 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
namespace Hood\Utils;
class PassHash
{
/**
* 生成密码
* @param $pass
* @return string
*/
public static function makePass($pass)
{
$salt = self::genSalt();
return self::getCrypted($pass, $salt) . ':' . $salt;
}
/**
* 获取干扰码
* @param int $length
* @return string
*/
public static function genSalt($length = 32)
{
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$saltLen = strlen($salt);
$makePass = '';
for ($i = 0; $i < $length; $i++) {
$makePass .= $salt[mt_rand(0, $saltLen - 1)];
}
return $makePass;
}
/**
* 验证密码
* @param $inputPassword
* @param $password
* @return bool
*/
public static function authPassword($inputPassword, $password)
{
if (empty($password) || empty($inputPassword)) {
return false;
}
$passwordList = explode(':', trim($password));
if (count($passwordList) != 2) {
return false;
}
list($crypt, $salt) = $passwordList;
$decode = self::getCrypted($inputPassword, $salt);
if ($crypt != $decode) {
return false;
}
return true;
}
public static function getCrypted($str, $salt = null)
{
return md5(crypt($str, $salt));
}
private static $algo = '$2a';
private static $cost = '$10';
public static function uniqueSalt()
{
return substr(sha1(mt_rand()), 0, 22);
}
/**
* hash加密
* @param $password
* @return string
*/
public static function hash($password)
{
return crypt($password,
self::$algo .
self::$cost .
'$' . self::uniqueSalt());
}
/**
* hash验证输入密码
* @param $hash
* @param $password
* @return bool
*/
public static function checkPassword($hash, $password)
{
$full_salt = substr($hash, 0, 29);
$new_hash = crypt($password, $full_salt);
return ($hash == $new_hash);
}
/**
* 双向加密
* @param $pass
* @return string
*/
public static function makeHashPass($pass)
{
$salt = self::hash($pass);
return self::getCrypted($pass, $salt) . ':' . $salt;
}
/**
* 双向验证
* @param $inputPassword
* @param $checkPass
* @return bool
*/
public static function checkHashPass($inputPassword, $checkPass)
{
if (empty($checkPass) || empty($inputPassword)) {
return false;
}
$passwordList = explode(':', trim($checkPass));
if (count($passwordList) != 2) {
return false;
}
list($crypt, $salt) = $passwordList;
$decode = self::getCrypted($inputPassword, $salt);
$hashCheck = self::checkPassword($salt, $inputPassword);
if (($crypt == $decode) && $hashCheck == true) {
return true;
}
return false;
}
}