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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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()](http://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()](http://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 | /** |
||
78 | * @var int Default cost used for password hashing. |
||
79 | * Allowed value is between 4 and 31. |
||
80 | * @see generatePasswordHash() |
||
81 | * @since 2.0.6 |
||
82 | */ |
||
83 | public $passwordHashCost = 13; |
||
84 | |||
85 | |||
86 | /** |
||
87 | * Encrypts data using a password. |
||
88 | * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt, |
||
89 | * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to |
||
90 | * encrypt fast using a cryptographic key rather than a password. Key derivation time is |
||
91 | * determined by [[$derivationIterations]], which should be set as high as possible. |
||
92 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
93 | * to hash input or output data. |
||
94 | * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against |
||
95 | * poor-quality or compromised passwords. |
||
96 | * @param string $data the data to encrypt |
||
97 | * @param string $password the password to use for encryption |
||
98 | * @return string the encrypted data |
||
99 | * @see decryptByPassword() |
||
100 | * @see encryptByKey() |
||
101 | */ |
||
102 | 1 | public function encryptByPassword($data, $password) |
|
106 | |||
107 | /** |
||
108 | * Encrypts data using a cryptographic key. |
||
109 | * Derives keys for encryption and authentication from the input key using HKDF and a random salt, |
||
110 | * which is very fast relative to [[encryptByPassword()]]. The input key must be properly |
||
111 | * random -- use [[generateRandomKey()]] to generate keys. |
||
112 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
113 | * to hash input or output data. |
||
114 | * @param string $data the data to encrypt |
||
115 | * @param string $inputKey the input to use for encryption and authentication |
||
116 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
117 | * @return string the encrypted data |
||
118 | * @see decryptByKey() |
||
119 | * @see encryptByPassword() |
||
120 | */ |
||
121 | 1 | public function encryptByKey($data, $inputKey, $info = null) |
|
125 | |||
126 | /** |
||
127 | * Verifies and decrypts data encrypted with [[encryptByPassword()]]. |
||
128 | * @param string $data the encrypted data to decrypt |
||
129 | * @param string $password the password to use for decryption |
||
130 | * @return bool|string the decrypted data or false on authentication failure |
||
131 | * @see encryptByPassword() |
||
132 | */ |
||
133 | 10 | public function decryptByPassword($data, $password) |
|
137 | |||
138 | /** |
||
139 | * Verifies and decrypts data encrypted with [[encryptByKey()]]. |
||
140 | * @param string $data the encrypted data to decrypt |
||
141 | * @param string $inputKey the input to use for encryption and authentication |
||
142 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
143 | * @return bool|string the decrypted data or false on authentication failure |
||
144 | * @see encryptByKey() |
||
145 | */ |
||
146 | 10 | public function decryptByKey($data, $inputKey, $info = null) |
|
150 | |||
151 | /** |
||
152 | * Encrypts data. |
||
153 | * |
||
154 | * @param string $data data to be encrypted |
||
155 | * @param bool $passwordBased set true to use password-based key derivation |
||
156 | * @param string $secret the encryption password or key |
||
157 | * @param string|null $info context/application specific information, e.g. a user ID |
||
158 | * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
||
159 | * |
||
160 | * @return string the encrypted data |
||
161 | * @throws InvalidConfigException on OpenSSL not loaded |
||
162 | * @throws Exception on OpenSSL error |
||
163 | * @see decrypt() |
||
164 | */ |
||
165 | 2 | protected function encrypt($data, $passwordBased, $secret, $info) |
|
201 | |||
202 | /** |
||
203 | * Decrypts data. |
||
204 | * |
||
205 | * @param string $data encrypted data to be decrypted. |
||
206 | * @param bool $passwordBased set true to use password-based key derivation |
||
207 | * @param string $secret the decryption password or key |
||
208 | * @param string|null $info context/application specific information, @see encrypt() |
||
209 | * |
||
210 | * @return bool|string the decrypted data or false on authentication failure |
||
211 | * @throws InvalidConfigException on OpenSSL not loaded |
||
212 | * @throws Exception on OpenSSL error |
||
213 | * @see encrypt() |
||
214 | */ |
||
215 | 20 | protected function decrypt($data, $passwordBased, $secret, $info) |
|
249 | |||
250 | /** |
||
251 | * Derives a key from the given input key using the standard HKDF algorithm. |
||
252 | * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869). |
||
253 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
254 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
255 | * @param string $inputKey the source key |
||
256 | * @param string $salt the random salt |
||
257 | * @param string $info optional info to bind the derived key material to application- |
||
258 | * and context-specific information, e.g. a user ID or API version, see |
||
259 | * [RFC 5869](https://tools.ietf.org/html/rfc5869) |
||
260 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
261 | * the length of the hash algorithm output. |
||
262 | * @throws InvalidArgumentException when HMAC generation fails. |
||
263 | * @return string the derived key |
||
264 | */ |
||
265 | 27 | public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0) |
|
305 | |||
306 | /** |
||
307 | * Derives a key from the given password using the standard PBKDF2 algorithm. |
||
308 | * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2) |
||
309 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
310 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
311 | * @param string $password the source password |
||
312 | * @param string $salt the random salt |
||
313 | * @param int $iterations the number of iterations of the hash algorithm. Set as high as |
||
314 | * possible to hinder dictionary password attacks. |
||
315 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
316 | * the length of the hash algorithm output. |
||
317 | * @return string the derived key |
||
318 | * @throws InvalidArgumentException when hash generation fails due to invalid params given. |
||
319 | */ |
||
320 | 19 | public function pbkdf2($algo, $password, $salt, $iterations, $length = 0) |
|
328 | |||
329 | /** |
||
330 | * Prefixes data with a keyed hash value so that it can later be detected if it is tampered. |
||
331 | * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]] |
||
332 | * as those methods perform the task. |
||
333 | * @param string $data the data to be protected |
||
334 | * @param string $key the secret key to be used for generating hash. Should be a secure |
||
335 | * cryptographic key. |
||
336 | * @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase |
||
337 | * hex digits will be generated. |
||
338 | * @return string the data prefixed with the keyed hash |
||
339 | * @throws InvalidConfigException when HMAC generation fails. |
||
340 | * @see validateData() |
||
341 | * @see generateRandomKey() |
||
342 | * @see hkdf() |
||
343 | * @see pbkdf2() |
||
344 | */ |
||
345 | 3 | public function hashData($data, $key, $rawHash = false) |
|
353 | |||
354 | /** |
||
355 | * Validates if the given data is tampered. |
||
356 | * @param string $data the data to be validated. The data must be previously |
||
357 | * generated by [[hashData()]]. |
||
358 | * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]]. |
||
359 | * function to see the supported hashing algorithms on your system. This must be the same |
||
360 | * as the value passed to [[hashData()]] when generating the hash for the data. |
||
361 | * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]]. |
||
362 | * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists |
||
363 | * of lowercase hex digits only. |
||
364 | * hex digits will be generated. |
||
365 | * @return string|false the real data with the hash stripped off. False if the data is tampered. |
||
366 | * @throws InvalidConfigException when HMAC generation fails. |
||
367 | * @see hashData() |
||
368 | */ |
||
369 | 21 | public function validateData($data, $key, $rawHash = false) |
|
388 | |||
389 | /** |
||
390 | * Generates specified number of random bytes. |
||
391 | * Note that output may not be ASCII. |
||
392 | * @see generateRandomString() if you need a string. |
||
393 | * |
||
394 | * @param int $length the number of bytes to generate |
||
395 | * @return string the generated random bytes |
||
396 | * @throws InvalidArgumentException if wrong length is specified |
||
397 | * @throws Exception on failure. |
||
398 | */ |
||
399 | 67 | public function generateRandomKey($length = 32) |
|
411 | |||
412 | /** |
||
413 | * Generates a random string of specified length. |
||
414 | * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding. |
||
415 | * |
||
416 | * @param int $length the length of the key in characters |
||
417 | * @return string the generated random key |
||
418 | * @throws Exception on failure. |
||
419 | */ |
||
420 | 14 | public function generateRandomString($length = 32) |
|
433 | |||
434 | /** |
||
435 | * Generates a secure hash from a password and a random salt. |
||
436 | * |
||
437 | * The generated hash can be stored in database. |
||
438 | * Later when a password needs to be validated, the hash can be fetched and passed |
||
439 | * to [[validatePassword()]]. For example, |
||
440 | * |
||
441 | * ```php |
||
442 | * // generates the hash (usually done during user registration or when the password is changed) |
||
443 | * $hash = Yii::$app->getSecurity()->generatePasswordHash($password); |
||
444 | * // ...save $hash in database... |
||
445 | * |
||
446 | * // during login, validate if the password entered is correct using $hash fetched from database |
||
447 | * if (Yii::$app->getSecurity()->validatePassword($password, $hash) { |
||
448 | * // password is good |
||
449 | * } else { |
||
450 | * // password is bad |
||
451 | * } |
||
452 | * ``` |
||
453 | * |
||
454 | * @param string $password The password to be hashed. |
||
455 | * @param int $cost Cost parameter used by the Blowfish hash algorithm. |
||
456 | * The higher the value of cost, |
||
457 | * the longer it takes to generate the hash and to verify a password against it. Higher cost |
||
458 | * therefore slows down a brute-force attack. For best protection against brute-force attacks, |
||
459 | * set it to the highest value that is tolerable on production servers. The time taken to |
||
460 | * compute the hash doubles for every increment by one of $cost. |
||
461 | * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', |
||
462 | * the output is always 60 ASCII characters, when set to 'password_hash' the output length |
||
463 | * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php) |
||
464 | * @throws Exception on bad password parameter or cost parameter. |
||
465 | * @see validatePassword() |
||
466 | */ |
||
467 | 1 | public function generatePasswordHash($password, $cost = null) |
|
476 | |||
477 | /** |
||
478 | * Verifies a password against a hash. |
||
479 | * @param string $password The password to verify. |
||
480 | * @param string $hash The hash to verify the password against. |
||
481 | * @return bool whether the password is correct. |
||
482 | * @throws InvalidArgumentException on bad password/hash parameters or if crypt() with Blowfish hash is not |
||
483 | * available. |
||
484 | * @see generatePasswordHash() |
||
485 | */ |
||
486 | 1 | public function validatePassword($password, $hash) |
|
501 | |||
502 | /** |
||
503 | * Performs string comparison using timing attack resistant approach. |
||
504 | * |
||
505 | * @param string $expected string to compare. |
||
506 | * @param string $actual user-supplied string. |
||
507 | * @return bool whether strings are equal. |
||
508 | */ |
||
509 | public function compareString($expected, $actual) |
||
513 | |||
514 | /** |
||
515 | * Masks a token to make it uncompressible. |
||
516 | * Applies a random mask to the token and prepends the mask used to the result making the string always unique. |
||
517 | * Used to mitigate BREACH attack by randomizing how token is outputted on each request. |
||
518 | * @param string $token An unmasked token. |
||
519 | * @return string A masked token. |
||
520 | * @since 2.0.12 |
||
521 | */ |
||
522 | 38 | public function maskToken($token) |
|
528 | |||
529 | /** |
||
530 | * Unmasks a token previously masked by `maskToken`. |
||
531 | * @param string $maskedToken A masked token. |
||
532 | * @return string An unmasked token, or an empty string in case of token format is invalid. |
||
533 | * @since 2.0.12 |
||
534 | */ |
||
535 | 8 | public function unmaskToken($maskedToken) |
|
545 | } |
||
546 |
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.