/
PhpassPasswordHash.php
314 lines (296 loc) · 11.2 KB
/
PhpassPasswordHash.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
declare(strict_types = 1);
namespace TYPO3\CMS\Core\Crypto\PasswordHashing;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Crypto\Random;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Class that implements PHPass salted hashing based on Drupal's
* modified Openwall implementation.
*
* Derived from Drupal CMS
* original license: GNU General Public License (GPL)
*
* PHPass should work on every system.
* @see http://drupal.org/node/29706/
* @see http://www.openwall.com/phpass/
*/
class PhpassPasswordHash implements PasswordHashInterface
{
/**
* Prefix for the password hash.
*/
protected const PREFIX = '$P$';
/**
* @var array The default log2 number of iterations for password stretching.
*/
protected $options = [
'hash_count' => 14
];
/**
* Constructor sets options if given
*
* @param array $options
*/
public function __construct(array $options = [])
{
$newOptions = $this->options;
if (isset($options['hash_count'])) {
if ((int)$options['hash_count'] < 7 || (int)$options['hash_count'] > 24) {
throw new \InvalidArgumentException(
'hash_count must not be lower than 7 or bigger than 24',
1533940454
);
}
$newOptions['hash_count'] = (int)$options['hash_count'];
}
$this->options = $newOptions;
}
/**
* Method checks if a given plaintext password is correct by comparing it with
* a given salted hashed password.
*
* @param string $plainPW Plain-text password to compare with salted hash
* @param string $saltedHashPW Salted hash to compare plain-text password with
* @return bool TRUE, if plain-text password matches the salted hash, otherwise FALSE
*/
public function checkPassword(string $plainPW, string $saltedHashPW): bool
{
$hash = $this->cryptPassword($plainPW, $saltedHashPW);
return $hash && hash_equals($hash, $saltedHashPW);
}
/**
* Returns whether all prerequisites for the hashing methods are matched
*
* @return bool Method available
*/
public function isAvailable(): bool
{
return true;
}
/**
* Method creates a salted hash for a given plaintext password
*
* @param string $password Plaintext password to create a salted hash from
* @return string|null salted hashed password
*/
public function getHashedPassword(string $password)
{
$saltedPW = null;
if (!empty($password)) {
$salt = $this->getGeneratedSalt();
$saltedPW = $this->cryptPassword($password, $this->applySettingsToSalt($salt));
}
return $saltedPW;
}
/**
* Checks whether a user's hashed password needs to be replaced with a new hash.
*
* This is typically called during the login process when the plain text
* password is available. A new hash is needed when the desired iteration
* count has changed through a change in the variable $hashCount or HASH_COUNT.
*
* @param string $passString Salted hash to check if it needs an update
* @return bool TRUE if salted hash needs an update, otherwise FALSE
*/
public function isHashUpdateNeeded(string $passString): bool
{
// Check whether this was an updated password.
if (strncmp($passString, '$P$', 3) || strlen($passString) != 34) {
return true;
}
// Check whether the iteration count used differs from the standard number.
return $this->getCountLog2($passString) < $this->options['hash_count'];
}
/**
* Method determines if a given string is a valid salted hashed password.
*
* @param string $saltedPW String to check
* @return bool TRUE if it's valid salted hashed password, otherwise FALSE
*/
public function isValidSaltedPW(string $saltedPW): bool
{
$isValid = !strncmp(self::PREFIX, $saltedPW, strlen(self::PREFIX));
if ($isValid) {
$isValid = $this->isValidSalt($saltedPW);
}
return $isValid;
}
/**
* Method applies settings (prefix, hash count) to a salt.
*
* @param string $salt A salt to apply setting to
* @return string Salt with setting
*/
protected function applySettingsToSalt(string $salt): string
{
$saltWithSettings = $salt;
$reqLenBase64 = $this->getLengthBase64FromBytes(6);
// Salt without setting
if (strlen($salt) == $reqLenBase64) {
// We encode the final log2 iteration count in base 64.
$itoa64 = $this->getItoa64();
$saltWithSettings = self::PREFIX . $itoa64[$this->options['hash_count']];
$saltWithSettings .= $salt;
}
return $saltWithSettings;
}
/**
* Hashes a password using a secure stretched hash.
*
* By using a salt and repeated hashing the password is "stretched". Its
* security is increased because it becomes much more computationally costly
* for an attacker to try to break the hash by brute-force computation of the
* hashes of a large number of plain-text words or strings to find a match.
*
* @param string $password Plain-text password to hash
* @param string $setting An existing hash or the output of getGeneratedSalt()
* @return mixed A string containing the hashed password (and salt)
*/
protected function cryptPassword(string $password, string $setting)
{
$saltedPW = null;
$reqLenBase64 = $this->getLengthBase64FromBytes(6);
// Retrieving settings with salt
$setting = substr($setting, 0, strlen(self::PREFIX) + 1 + $reqLenBase64);
$count_log2 = $this->getCountLog2($setting);
// Hashes may be imported from elsewhere, so we allow != HASH_COUNT
if ($count_log2 >= 7 && $count_log2 <= 24) {
$salt = substr($setting, strlen(self::PREFIX) + 1, $reqLenBase64);
// We must use md5() or sha1() here since they are the only cryptographic
// primitives always available in PHP 5. To implement our own low-level
// cryptographic function in PHP would result in much worse performance and
// consequently in lower iteration counts and hashes that are quicker to crack
// (by non-PHP code).
$count = 1 << $count_log2;
$hash = md5($salt . $password, true);
do {
$hash = md5($hash . $password, true);
} while (--$count);
$saltedPW = $setting . $this->base64Encode($hash, 16);
// base64Encode() of a 16 byte MD5 will always be 22 characters.
return strlen($saltedPW) == 34 ? $saltedPW : false;
}
return $saltedPW;
}
/**
* Parses the log2 iteration count from a stored hash or setting string.
*
* @param string $setting Complete hash or a hash's setting string or to get log2 iteration count from
* @return int Used hashcount for given hash string
*/
protected function getCountLog2(string $setting): int
{
return strpos($this->getItoa64(), $setting[strlen(self::PREFIX)]);
}
/**
* Generates a random base 64-encoded salt prefixed and suffixed with settings for the hash.
*
* Proper use of salts may defeat a number of attacks, including:
* - The ability to try candidate passwords against multiple hashes at once.
* - The ability to use pre-hashed lists of candidate passwords.
* - The ability to determine whether two users have the same (or different)
* password without actually having to guess one of the passwords.
*
* @return string A character string containing settings and a random salt
*/
protected function getGeneratedSalt(): string
{
$randomBytes = GeneralUtility::makeInstance(Random::class)->generateRandomBytes(6);
return $this->base64Encode($randomBytes, 6);
}
/**
* Returns a string for mapping an int to the corresponding base 64 character.
*
* @return string String for mapping an int to the corresponding base 64 character
*/
protected function getItoa64(): string
{
return './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
}
/**
* Method determines if a given string is a valid salt.
*
* @param string $salt String to check
* @return bool TRUE if it's valid salt, otherwise FALSE
*/
protected function isValidSalt(string $salt): bool
{
$isValid = ($skip = false);
$reqLenBase64 = $this->getLengthBase64FromBytes(6);
if (strlen($salt) >= $reqLenBase64) {
// Salt with prefixed setting
if (!strncmp('$', $salt, 1)) {
if (!strncmp(self::PREFIX, $salt, strlen(self::PREFIX))) {
$isValid = true;
$salt = substr($salt, strrpos($salt, '$') + 2);
} else {
$skip = true;
}
}
// Checking base64 characters
if (!$skip && strlen($salt) >= $reqLenBase64) {
if (preg_match('/^[' . preg_quote($this->getItoa64(), '/') . ']{' . $reqLenBase64 . ',' . $reqLenBase64 . '}$/', substr($salt, 0, $reqLenBase64))) {
$isValid = true;
}
}
}
return $isValid;
}
/**
* Encodes bytes into printable base 64 using the *nix standard from crypt().
*
* @param string $input The string containing bytes to encode.
* @param int $count The number of characters (bytes) to encode.
* @return string Encoded string
*/
protected function base64Encode(string $input, int $count): string
{
$output = '';
$i = 0;
$itoa64 = $this->getItoa64();
do {
$value = ord($input[$i++]);
$output .= $itoa64[$value & 63];
if ($i < $count) {
$value |= ord($input[$i]) << 8;
}
$output .= $itoa64[$value >> 6 & 63];
if ($i++ >= $count) {
break;
}
if ($i < $count) {
$value |= ord($input[$i]) << 16;
}
$output .= $itoa64[$value >> 12 & 63];
if ($i++ >= $count) {
break;
}
$output .= $itoa64[$value >> 18 & 63];
} while ($i < $count);
return $output;
}
/**
* Method determines required length of base64 characters for a given
* length of a byte string.
*
* @param int $byteLength Length of bytes to calculate in base64 chars
* @return int Required length of base64 characters
*/
protected function getLengthBase64FromBytes(int $byteLength): int
{
// Calculates bytes in bits in base64
return (int)ceil($byteLength * 8 / 6);
}
}