Total Complexity | 86 |
Total Lines | 673 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like Security often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Security, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
33 | class Security extends Component |
||
34 | { |
||
35 | /** |
||
36 | * @var string The cipher to use for encryption and decryption. |
||
37 | */ |
||
38 | public $cipher = 'AES-128-CBC'; |
||
39 | /** |
||
40 | * @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher. |
||
41 | * |
||
42 | * In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()). |
||
43 | * The value is an array of two integers, the first is the cipher's block size in bytes and the second is |
||
44 | * the key size in bytes. |
||
45 | * |
||
46 | * > Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode. |
||
47 | * |
||
48 | * > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key |
||
49 | * derivation salt. |
||
50 | */ |
||
51 | public $allowedCiphers = [ |
||
52 | 'AES-128-CBC' => [16, 16], |
||
53 | 'AES-192-CBC' => [16, 24], |
||
54 | 'AES-256-CBC' => [16, 32], |
||
55 | ]; |
||
56 | /** |
||
57 | * @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512. |
||
58 | * @see [hash_algos()](https://secure.php.net/manual/en/function.hash-algos.php) |
||
59 | */ |
||
60 | public $kdfHash = 'sha256'; |
||
61 | /** |
||
62 | * @var string Hash algorithm for message authentication. Recommend sha256, sha384 or sha512. |
||
63 | * @see [hash_algos()](https://secure.php.net/manual/en/function.hash-algos.php) |
||
64 | */ |
||
65 | public $macHash = 'sha256'; |
||
66 | /** |
||
67 | * @var string HKDF info value for derivation of message authentication key. |
||
68 | * @see hkdf() |
||
69 | */ |
||
70 | public $authKeyInfo = 'AuthorizationKey'; |
||
71 | /** |
||
72 | * @var int derivation iterations count. |
||
73 | * Set as high as possible to hinder dictionary password attacks. |
||
74 | */ |
||
75 | public $derivationIterations = 100000; |
||
76 | /** |
||
77 | * @var string strategy, which should be used to generate password hash. |
||
78 | * Available strategies: |
||
79 | * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm. |
||
80 | * This option is recommended, but it requires PHP version >= 5.5.0 |
||
81 | * - 'crypt' - use PHP `crypt()` function. |
||
82 | * @deprecated since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and |
||
83 | * uses `password_hash()` when available or `crypt()` when not. |
||
84 | */ |
||
85 | public $passwordHashStrategy; |
||
86 | /** |
||
87 | * @var int Default cost used for password hashing. |
||
88 | * Allowed value is between 4 and 31. |
||
89 | * @see generatePasswordHash() |
||
90 | * @since 2.0.6 |
||
91 | */ |
||
92 | public $passwordHashCost = 13; |
||
93 | |||
94 | /** |
||
95 | * @var boolean if LibreSSL should be used. |
||
96 | * The recent (> 2.1.5) LibreSSL RNGs are faster and likely better than /dev/urandom. |
||
97 | */ |
||
98 | private $_useLibreSSL; |
||
99 | |||
100 | |||
101 | /** |
||
102 | * @return bool if LibreSSL should be used |
||
103 | * Use version is 2.1.5 or higher. |
||
104 | * @since 2.0.36 |
||
105 | */ |
||
106 | protected function shouldUseLibreSSL() |
||
117 | } |
||
118 | |||
119 | /** |
||
120 | * Encrypts data using a password. |
||
121 | * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt, |
||
122 | * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to |
||
123 | * encrypt fast using a cryptographic key rather than a password. Key derivation time is |
||
124 | * determined by [[$derivationIterations]], which should be set as high as possible. |
||
125 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
126 | * to hash input or output data. |
||
127 | * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against |
||
128 | * poor-quality or compromised passwords. |
||
129 | * @param string $data the data to encrypt |
||
130 | * @param string $password the password to use for encryption |
||
131 | * @return string the encrypted data as byte string |
||
132 | * @see decryptByPassword() |
||
133 | * @see encryptByKey() |
||
134 | */ |
||
135 | public function encryptByPassword($data, $password) |
||
136 | { |
||
137 | return $this->encrypt($data, true, $password, null); |
||
138 | } |
||
139 | |||
140 | /** |
||
141 | * Encrypts data using a cryptographic key. |
||
142 | * Derives keys for encryption and authentication from the input key using HKDF and a random salt, |
||
143 | * which is very fast relative to [[encryptByPassword()]]. The input key must be properly |
||
144 | * random -- use [[generateRandomKey()]] to generate keys. |
||
145 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
146 | * to hash input or output data. |
||
147 | * @param string $data the data to encrypt |
||
148 | * @param string $inputKey the input to use for encryption and authentication |
||
149 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
150 | * @return string the encrypted data as byte string |
||
151 | * @see decryptByKey() |
||
152 | * @see encryptByPassword() |
||
153 | */ |
||
154 | public function encryptByKey($data, $inputKey, $info = null) |
||
155 | { |
||
156 | return $this->encrypt($data, false, $inputKey, $info); |
||
157 | } |
||
158 | |||
159 | /** |
||
160 | * Verifies and decrypts data encrypted with [[encryptByPassword()]]. |
||
161 | * @param string $data the encrypted data to decrypt |
||
162 | * @param string $password the password to use for decryption |
||
163 | * @return bool|string the decrypted data or false on authentication failure |
||
164 | * @see encryptByPassword() |
||
165 | */ |
||
166 | public function decryptByPassword($data, $password) |
||
167 | { |
||
168 | return $this->decrypt($data, true, $password, null); |
||
169 | } |
||
170 | |||
171 | /** |
||
172 | * Verifies and decrypts data encrypted with [[encryptByKey()]]. |
||
173 | * @param string $data the encrypted data to decrypt |
||
174 | * @param string $inputKey the input to use for encryption and authentication |
||
175 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
176 | * @return bool|string the decrypted data or false on authentication failure |
||
177 | * @see encryptByKey() |
||
178 | */ |
||
179 | public function decryptByKey($data, $inputKey, $info = null) |
||
180 | { |
||
181 | return $this->decrypt($data, false, $inputKey, $info); |
||
182 | } |
||
183 | |||
184 | /** |
||
185 | * Encrypts data. |
||
186 | * |
||
187 | * @param string $data data to be encrypted |
||
188 | * @param bool $passwordBased set true to use password-based key derivation |
||
189 | * @param string $secret the encryption password or key |
||
190 | * @param string|null $info context/application specific information, e.g. a user ID |
||
191 | * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
||
192 | * |
||
193 | * @return string the encrypted data as byte string |
||
194 | * @throws InvalidConfigException on OpenSSL not loaded |
||
195 | * @throws Exception on OpenSSL error |
||
196 | * @see decrypt() |
||
197 | */ |
||
198 | protected function encrypt($data, $passwordBased, $secret, $info) |
||
199 | { |
||
200 | if (!extension_loaded('openssl')) { |
||
201 | throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension'); |
||
202 | } |
||
203 | if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) { |
||
204 | throw new InvalidConfigException($this->cipher . ' is not an allowed cipher'); |
||
205 | } |
||
206 | |||
207 | list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher]; |
||
208 | |||
209 | $keySalt = $this->generateRandomKey($keySize); |
||
210 | if ($passwordBased) { |
||
211 | $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize); |
||
212 | } else { |
||
213 | $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize); |
||
214 | } |
||
215 | |||
216 | $iv = $this->generateRandomKey($blockSize); |
||
217 | |||
218 | $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv); |
||
219 | if ($encrypted === false) { |
||
220 | throw new \yii\base\Exception('OpenSSL failure on encryption: ' . openssl_error_string()); |
||
221 | } |
||
222 | |||
223 | $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize); |
||
224 | $hashed = $this->hashData($iv . $encrypted, $authKey); |
||
225 | |||
226 | /* |
||
227 | * Output: [keySalt][MAC][IV][ciphertext] |
||
228 | * - keySalt is KEY_SIZE bytes long |
||
229 | * - MAC: message authentication code, length same as the output of MAC_HASH |
||
230 | * - IV: initialization vector, length $blockSize |
||
231 | */ |
||
232 | return $keySalt . $hashed; |
||
233 | } |
||
234 | |||
235 | /** |
||
236 | * Decrypts data. |
||
237 | * |
||
238 | * @param string $data encrypted data to be decrypted. |
||
239 | * @param bool $passwordBased set true to use password-based key derivation |
||
240 | * @param string $secret the decryption password or key |
||
241 | * @param string|null $info context/application specific information, @see encrypt() |
||
242 | * |
||
243 | * @return bool|string the decrypted data or false on authentication failure |
||
244 | * @throws InvalidConfigException on OpenSSL not loaded |
||
245 | * @throws Exception on OpenSSL error |
||
246 | * @see encrypt() |
||
247 | */ |
||
248 | protected function decrypt($data, $passwordBased, $secret, $info) |
||
249 | { |
||
250 | if (!extension_loaded('openssl')) { |
||
251 | throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension'); |
||
252 | } |
||
253 | if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) { |
||
254 | throw new InvalidConfigException($this->cipher . ' is not an allowed cipher'); |
||
255 | } |
||
256 | |||
257 | list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher]; |
||
258 | |||
259 | $keySalt = StringHelper::byteSubstr($data, 0, $keySize); |
||
260 | if ($passwordBased) { |
||
261 | $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize); |
||
262 | } else { |
||
263 | $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize); |
||
264 | } |
||
265 | |||
266 | $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize); |
||
267 | $data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey); |
||
268 | if ($data === false) { |
||
269 | return false; |
||
270 | } |
||
271 | |||
272 | $iv = StringHelper::byteSubstr($data, 0, $blockSize); |
||
273 | $encrypted = StringHelper::byteSubstr($data, $blockSize, null); |
||
274 | |||
275 | $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv); |
||
276 | if ($decrypted === false) { |
||
277 | throw new \yii\base\Exception('OpenSSL failure on decryption: ' . openssl_error_string()); |
||
278 | } |
||
279 | |||
280 | return $decrypted; |
||
281 | } |
||
282 | |||
283 | /** |
||
284 | * Derives a key from the given input key using the standard HKDF algorithm. |
||
285 | * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869). |
||
286 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
287 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
288 | * @param string $inputKey the source key |
||
289 | * @param string $salt the random salt |
||
290 | * @param string $info optional info to bind the derived key material to application- |
||
291 | * and context-specific information, e.g. a user ID or API version, see |
||
292 | * [RFC 5869](https://tools.ietf.org/html/rfc5869) |
||
293 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
294 | * the length of the hash algorithm output. |
||
295 | * @throws InvalidArgumentException when HMAC generation fails. |
||
296 | * @return string the derived key |
||
297 | */ |
||
298 | public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0) |
||
299 | { |
||
300 | if (function_exists('hash_hkdf')) { |
||
301 | $outputKey = hash_hkdf($algo, $inputKey, $length, $info, $salt); |
||
302 | if ($outputKey === false) { |
||
303 | throw new InvalidArgumentException('Invalid parameters to hash_hkdf()'); |
||
304 | } |
||
305 | |||
306 | return $outputKey; |
||
307 | } |
||
308 | |||
309 | $test = @hash_hmac($algo, '', '', true); |
||
310 | if (!$test) { |
||
311 | throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo); |
||
312 | } |
||
313 | $hashLength = StringHelper::byteLength($test); |
||
314 | if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) { |
||
315 | $length = (int) $length; |
||
316 | } |
||
317 | if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) { |
||
318 | throw new InvalidArgumentException('Invalid length'); |
||
319 | } |
||
320 | $blocks = $length !== 0 ? ceil($length / $hashLength) : 1; |
||
321 | |||
322 | if ($salt === null) { |
||
323 | $salt = str_repeat("\0", $hashLength); |
||
324 | } |
||
325 | $prKey = hash_hmac($algo, $inputKey, $salt, true); |
||
326 | |||
327 | $hmac = ''; |
||
328 | $outputKey = ''; |
||
329 | for ($i = 1; $i <= $blocks; $i++) { |
||
330 | $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true); |
||
331 | $outputKey .= $hmac; |
||
332 | } |
||
333 | |||
334 | if ($length !== 0) { |
||
335 | $outputKey = StringHelper::byteSubstr($outputKey, 0, $length); |
||
336 | } |
||
337 | |||
338 | return $outputKey; |
||
339 | } |
||
340 | |||
341 | /** |
||
342 | * Derives a key from the given password using the standard PBKDF2 algorithm. |
||
343 | * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2) |
||
344 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
345 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
346 | * @param string $password the source password |
||
347 | * @param string $salt the random salt |
||
348 | * @param int $iterations the number of iterations of the hash algorithm. Set as high as |
||
349 | * possible to hinder dictionary password attacks. |
||
350 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
351 | * the length of the hash algorithm output. |
||
352 | * @return string the derived key |
||
353 | * @throws InvalidArgumentException when hash generation fails due to invalid params given. |
||
354 | */ |
||
355 | public function pbkdf2($algo, $password, $salt, $iterations, $length = 0) |
||
356 | { |
||
357 | if (function_exists('hash_pbkdf2') && PHP_VERSION_ID >= 50500) { |
||
358 | $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true); |
||
359 | if ($outputKey === false) { |
||
360 | throw new InvalidArgumentException('Invalid parameters to hash_pbkdf2()'); |
||
361 | } |
||
362 | |||
363 | return $outputKey; |
||
364 | } |
||
365 | |||
366 | // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()? |
||
367 | $test = @hash_hmac($algo, '', '', true); |
||
368 | if (!$test) { |
||
369 | throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo); |
||
370 | } |
||
371 | if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) { |
||
372 | $iterations = (int) $iterations; |
||
373 | } |
||
374 | if (!is_int($iterations) || $iterations < 1) { |
||
375 | throw new InvalidArgumentException('Invalid iterations'); |
||
376 | } |
||
377 | if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) { |
||
378 | $length = (int) $length; |
||
379 | } |
||
380 | if (!is_int($length) || $length < 0) { |
||
381 | throw new InvalidArgumentException('Invalid length'); |
||
382 | } |
||
383 | $hashLength = StringHelper::byteLength($test); |
||
384 | $blocks = $length !== 0 ? ceil($length / $hashLength) : 1; |
||
385 | |||
386 | $outputKey = ''; |
||
387 | for ($j = 1; $j <= $blocks; $j++) { |
||
388 | $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true); |
||
389 | $xorsum = $hmac; |
||
390 | for ($i = 1; $i < $iterations; $i++) { |
||
391 | $hmac = hash_hmac($algo, $hmac, $password, true); |
||
392 | $xorsum ^= $hmac; |
||
393 | } |
||
394 | $outputKey .= $xorsum; |
||
395 | } |
||
396 | |||
397 | if ($length !== 0) { |
||
398 | $outputKey = StringHelper::byteSubstr($outputKey, 0, $length); |
||
399 | } |
||
400 | |||
401 | return $outputKey; |
||
402 | } |
||
403 | |||
404 | /** |
||
405 | * Prefixes data with a keyed hash value so that it can later be detected if it is tampered. |
||
406 | * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]] |
||
407 | * as those methods perform the task. |
||
408 | * @param string $data the data to be protected |
||
409 | * @param string $key the secret key to be used for generating hash. Should be a secure |
||
410 | * cryptographic key. |
||
411 | * @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase |
||
412 | * hex digits will be generated. |
||
413 | * @return string the data prefixed with the keyed hash |
||
414 | * @throws InvalidConfigException when HMAC generation fails. |
||
415 | * @see validateData() |
||
416 | * @see generateRandomKey() |
||
417 | * @see hkdf() |
||
418 | * @see pbkdf2() |
||
419 | */ |
||
420 | public function hashData($data, $key, $rawHash = false) |
||
421 | { |
||
422 | $hash = hash_hmac($this->macHash, $data, $key, $rawHash); |
||
423 | if (!$hash) { |
||
424 | throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash); |
||
425 | } |
||
426 | |||
427 | return $hash . $data; |
||
428 | } |
||
429 | |||
430 | /** |
||
431 | * Validates if the given data is tampered. |
||
432 | * @param string $data the data to be validated. The data must be previously |
||
433 | * generated by [[hashData()]]. |
||
434 | * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]]. |
||
435 | * function to see the supported hashing algorithms on your system. This must be the same |
||
436 | * as the value passed to [[hashData()]] when generating the hash for the data. |
||
437 | * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]]. |
||
438 | * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists |
||
439 | * of lowercase hex digits only. |
||
440 | * hex digits will be generated. |
||
441 | * @return string|false the real data with the hash stripped off. False if the data is tampered. |
||
442 | * @throws InvalidConfigException when HMAC generation fails. |
||
443 | * @see hashData() |
||
444 | */ |
||
445 | public function validateData($data, $key, $rawHash = false) |
||
446 | { |
||
447 | $test = @hash_hmac($this->macHash, '', '', $rawHash); |
||
448 | if (!$test) { |
||
449 | throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash); |
||
450 | } |
||
451 | $hashLength = StringHelper::byteLength($test); |
||
452 | if (StringHelper::byteLength($data) >= $hashLength) { |
||
453 | $hash = StringHelper::byteSubstr($data, 0, $hashLength); |
||
454 | $pureData = StringHelper::byteSubstr($data, $hashLength, null); |
||
455 | |||
456 | $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash); |
||
457 | |||
458 | if ($this->compareString($hash, $calculatedHash)) { |
||
459 | return $pureData; |
||
460 | } |
||
461 | } |
||
462 | |||
463 | return false; |
||
464 | } |
||
465 | |||
466 | /** |
||
467 | * Generates specified number of random bytes. |
||
468 | * Note that output may not be ASCII. |
||
469 | * @see generateRandomString() if you need a string. |
||
470 | * |
||
471 | * @param int $length the number of bytes to generate |
||
472 | * @return string the generated random bytes |
||
473 | * @throws InvalidArgumentException if wrong length is specified |
||
474 | * @throws Exception on failure. |
||
475 | */ |
||
476 | public function generateRandomKey($length = 32) |
||
477 | { |
||
478 | if (!is_int($length)) { |
||
479 | throw new InvalidArgumentException('First parameter ($length) must be an integer'); |
||
480 | } |
||
481 | |||
482 | if ($length < 1) { |
||
483 | throw new InvalidArgumentException('First parameter ($length) must be greater than 0'); |
||
484 | } |
||
485 | |||
486 | return random_bytes($length); |
||
487 | } |
||
488 | |||
489 | /** |
||
490 | * Generates random integer in a given range. |
||
491 | * |
||
492 | * @param int $min Minimum value. |
||
493 | * @param int $max Maximum value. |
||
494 | * @return int |
||
495 | * @throws \Exception If unable to generate random integer. |
||
496 | * @since 2.0.43 |
||
497 | */ |
||
498 | public function generateRandomInt($min, $max) |
||
501 | } |
||
502 | |||
503 | /** |
||
504 | * Generates a random string of specified length. |
||
505 | * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding. |
||
506 | * |
||
507 | * @param int $length the length of the key in characters |
||
508 | * @return string the generated random key |
||
509 | * @throws Exception on failure. |
||
510 | */ |
||
511 | public function generateRandomString($length = 32) |
||
512 | { |
||
513 | if (!is_int($length)) { |
||
514 | throw new InvalidArgumentException('First parameter ($length) must be an integer'); |
||
515 | } |
||
516 | |||
517 | if ($length < 1) { |
||
518 | throw new InvalidArgumentException('First parameter ($length) must be greater than 0'); |
||
519 | } |
||
520 | |||
521 | $bytes = $this->generateRandomKey($length); |
||
522 | return substr(StringHelper::base64UrlEncode($bytes), 0, $length); |
||
523 | } |
||
524 | |||
525 | /** |
||
526 | * Generates a secure hash from a password and a random salt. |
||
527 | * |
||
528 | * The generated hash can be stored in database. |
||
529 | * Later when a password needs to be validated, the hash can be fetched and passed |
||
530 | * to [[validatePassword()]]. For example, |
||
531 | * |
||
532 | * ```php |
||
533 | * // generates the hash (usually done during user registration or when the password is changed) |
||
534 | * $hash = Yii::$app->getSecurity()->generatePasswordHash($password); |
||
535 | * // ...save $hash in database... |
||
536 | * |
||
537 | * // during login, validate if the password entered is correct using $hash fetched from database |
||
538 | * if (Yii::$app->getSecurity()->validatePassword($password, $hash)) { |
||
539 | * // password is good |
||
540 | * } else { |
||
541 | * // password is bad |
||
542 | * } |
||
543 | * ``` |
||
544 | * |
||
545 | * @param string $password The password to be hashed. |
||
546 | * @param int $cost Cost parameter used by the Blowfish hash algorithm. |
||
547 | * The higher the value of cost, |
||
548 | * the longer it takes to generate the hash and to verify a password against it. Higher cost |
||
549 | * therefore slows down a brute-force attack. For best protection against brute-force attacks, |
||
550 | * set it to the highest value that is tolerable on production servers. The time taken to |
||
551 | * compute the hash doubles for every increment by one of $cost. |
||
552 | * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', |
||
553 | * the output is always 60 ASCII characters, when set to 'password_hash' the output length |
||
554 | * might increase in future versions of PHP (https://secure.php.net/manual/en/function.password-hash.php) |
||
555 | * @throws Exception on bad password parameter or cost parameter. |
||
556 | * @see validatePassword() |
||
557 | */ |
||
558 | public function generatePasswordHash($password, $cost = null) |
||
577 | } |
||
578 | |||
579 | /** |
||
580 | * Verifies a password against a hash. |
||
581 | * @param string $password The password to verify. |
||
582 | * @param string $hash The hash to verify the password against. |
||
583 | * @return bool whether the password is correct. |
||
584 | * @throws InvalidArgumentException on bad password/hash parameters or if crypt() with Blowfish hash is not available. |
||
585 | * @see generatePasswordHash() |
||
586 | */ |
||
587 | public function validatePassword($password, $hash) |
||
588 | { |
||
589 | if (!is_string($password) || $password === '') { |
||
590 | throw new InvalidArgumentException('Password must be a string and cannot be empty.'); |
||
591 | } |
||
592 | |||
593 | if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) |
||
594 | || $matches[1] < 4 |
||
595 | || $matches[1] > 30 |
||
596 | ) { |
||
597 | throw new InvalidArgumentException('Hash is invalid.'); |
||
598 | } |
||
599 | |||
600 | if (function_exists('password_verify')) { |
||
601 | return password_verify($password, $hash); |
||
602 | } |
||
603 | |||
604 | $test = crypt($password, $hash); |
||
605 | $n = strlen($test); |
||
606 | if ($n !== 60) { |
||
607 | return false; |
||
608 | } |
||
609 | |||
610 | return $this->compareString($test, $hash); |
||
611 | } |
||
612 | |||
613 | /** |
||
614 | * Generates a salt that can be used to generate a password hash. |
||
615 | * |
||
616 | * The PHP [crypt()](https://secure.php.net/manual/en/function.crypt.php) built-in function |
||
617 | * requires, for the Blowfish hash algorithm, a salt string in a specific format: |
||
618 | * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters |
||
619 | * from the alphabet "./0-9A-Za-z". |
||
620 | * |
||
621 | * @param int $cost the cost parameter |
||
622 | * @return string the random salt value. |
||
623 | * @throws InvalidArgumentException if the cost parameter is out of the range of 4 to 31. |
||
624 | */ |
||
625 | protected function generateSalt($cost = 13) |
||
626 | { |
||
627 | $cost = (int) $cost; |
||
628 | if ($cost < 4 || $cost > 31) { |
||
629 | throw new InvalidArgumentException('Cost must be between 4 and 31.'); |
||
630 | } |
||
631 | |||
632 | // Get a 20-byte random string |
||
633 | $rand = $this->generateRandomKey(20); |
||
634 | // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter. |
||
635 | $salt = sprintf('$2y$%02d$', $cost); |
||
636 | // Append the random salt data in the required base64 format. |
||
637 | $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22)); |
||
638 | |||
639 | return $salt; |
||
640 | } |
||
641 | |||
642 | /** |
||
643 | * Performs string comparison using timing attack resistant approach. |
||
644 | * @see http://codereview.stackexchange.com/questions/13512 |
||
645 | * @param string $expected string to compare. |
||
646 | * @param string $actual user-supplied string. |
||
647 | * @return bool whether strings are equal. |
||
648 | */ |
||
649 | public function compareString($expected, $actual) |
||
673 | } |
||
674 | |||
675 | /** |
||
676 | * Masks a token to make it uncompressible. |
||
677 | * Applies a random mask to the token and prepends the mask used to the result making the string always unique. |
||
678 | * Used to mitigate BREACH attack by randomizing how token is outputted on each request. |
||
679 | * @param string $token An unmasked token. |
||
680 | * @return string A masked token. |
||
681 | * @since 2.0.12 |
||
682 | */ |
||
683 | public function maskToken($token) |
||
688 | } |
||
689 | |||
690 | /** |
||
691 | * Unmasks a token previously masked by `maskToken`. |
||
692 | * @param string $maskedToken A masked token. |
||
693 | * @return string An unmasked token, or an empty string in case of token format is invalid. |
||
694 | * @since 2.0.12 |
||
695 | */ |
||
696 | public function unmaskToken($maskedToken) |
||
706 | } |
||
707 | } |
||
708 |