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 | * @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 | /** |
||
| 96 | * Encrypts data using a password. |
||
| 97 | * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt, |
||
| 98 | * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to |
||
| 99 | * encrypt fast using a cryptographic key rather than a password. Key derivation time is |
||
| 100 | * determined by [[$derivationIterations]], which should be set as high as possible. |
||
| 101 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
| 102 | * to hash input or output data. |
||
| 103 | * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against |
||
| 104 | * poor-quality or compromised passwords. |
||
| 105 | * @param string $data the data to encrypt |
||
| 106 | * @param string $password the password to use for encryption |
||
| 107 | * @return string the encrypted data |
||
| 108 | * @see decryptByPassword() |
||
| 109 | * @see encryptByKey() |
||
| 110 | */ |
||
| 111 | 1 | public function encryptByPassword($data, $password) |
|
| 115 | |||
| 116 | /** |
||
| 117 | * Encrypts data using a cryptographic key. |
||
| 118 | * Derives keys for encryption and authentication from the input key using HKDF and a random salt, |
||
| 119 | * which is very fast relative to [[encryptByPassword()]]. The input key must be properly |
||
| 120 | * random -- use [[generateRandomKey()]] to generate keys. |
||
| 121 | * The encrypted data includes a keyed message authentication code (MAC) so there is no need |
||
| 122 | * to hash input or output data. |
||
| 123 | * @param string $data the data to encrypt |
||
| 124 | * @param string $inputKey the input to use for encryption and authentication |
||
| 125 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
| 126 | * @return string the encrypted data |
||
| 127 | * @see decryptByKey() |
||
| 128 | * @see encryptByPassword() |
||
| 129 | */ |
||
| 130 | 1 | public function encryptByKey($data, $inputKey, $info = null) |
|
| 134 | |||
| 135 | /** |
||
| 136 | * Verifies and decrypts data encrypted with [[encryptByPassword()]]. |
||
| 137 | * @param string $data the encrypted data to decrypt |
||
| 138 | * @param string $password the password to use for decryption |
||
| 139 | * @return bool|string the decrypted data or false on authentication failure |
||
| 140 | * @see encryptByPassword() |
||
| 141 | */ |
||
| 142 | 10 | public function decryptByPassword($data, $password) |
|
| 146 | |||
| 147 | /** |
||
| 148 | * Verifies and decrypts data encrypted with [[encryptByKey()]]. |
||
| 149 | * @param string $data the encrypted data to decrypt |
||
| 150 | * @param string $inputKey the input to use for encryption and authentication |
||
| 151 | * @param string $info optional context and application specific information, see [[hkdf()]] |
||
| 152 | * @return bool|string the decrypted data or false on authentication failure |
||
| 153 | * @see encryptByKey() |
||
| 154 | */ |
||
| 155 | 10 | public function decryptByKey($data, $inputKey, $info = null) |
|
| 159 | |||
| 160 | /** |
||
| 161 | * Encrypts data. |
||
| 162 | * |
||
| 163 | * @param string $data data to be encrypted |
||
| 164 | * @param bool $passwordBased set true to use password-based key derivation |
||
| 165 | * @param string $secret the encryption password or key |
||
| 166 | * @param string|null $info context/application specific information, e.g. a user ID |
||
| 167 | * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
||
| 168 | * |
||
| 169 | * @return string the encrypted data |
||
| 170 | * @throws InvalidConfigException on OpenSSL not loaded |
||
| 171 | * @throws Exception on OpenSSL error |
||
| 172 | * @see decrypt() |
||
| 173 | */ |
||
| 174 | 2 | protected function encrypt($data, $passwordBased, $secret, $info) |
|
| 210 | |||
| 211 | /** |
||
| 212 | * Decrypts data. |
||
| 213 | * |
||
| 214 | * @param string $data encrypted data to be decrypted. |
||
| 215 | * @param bool $passwordBased set true to use password-based key derivation |
||
| 216 | * @param string $secret the decryption password or key |
||
| 217 | * @param string|null $info context/application specific information, @see encrypt() |
||
| 218 | * |
||
| 219 | * @return bool|string the decrypted data or false on authentication failure |
||
| 220 | * @throws InvalidConfigException on OpenSSL not loaded |
||
| 221 | * @throws Exception on OpenSSL error |
||
| 222 | * @see encrypt() |
||
| 223 | */ |
||
| 224 | 20 | protected function decrypt($data, $passwordBased, $secret, $info) |
|
| 258 | |||
| 259 | /** |
||
| 260 | * Derives a key from the given input key using the standard HKDF algorithm. |
||
| 261 | * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869). |
||
| 262 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
| 263 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
| 264 | * @param string $inputKey the source key |
||
| 265 | * @param string $salt the random salt |
||
| 266 | * @param string $info optional info to bind the derived key material to application- |
||
| 267 | * and context-specific information, e.g. a user ID or API version, see |
||
| 268 | * [RFC 5869](https://tools.ietf.org/html/rfc5869) |
||
| 269 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
| 270 | * the length of the hash algorithm output. |
||
| 271 | * @throws InvalidParamException when HMAC generation fails. |
||
| 272 | * @return string the derived key |
||
| 273 | */ |
||
| 274 | 27 | public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0) |
|
| 316 | |||
| 317 | /** |
||
| 318 | * Derives a key from the given password using the standard PBKDF2 algorithm. |
||
| 319 | * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2) |
||
| 320 | * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512. |
||
| 321 | * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256' |
||
| 322 | * @param string $password the source password |
||
| 323 | * @param string $salt the random salt |
||
| 324 | * @param int $iterations the number of iterations of the hash algorithm. Set as high as |
||
| 325 | * possible to hinder dictionary password attacks. |
||
| 326 | * @param int $length length of the output key in bytes. If 0, the output key is |
||
| 327 | * the length of the hash algorithm output. |
||
| 328 | * @return string the derived key |
||
| 329 | * @throws InvalidParamException when hash generation fails due to invalid params given. |
||
| 330 | */ |
||
| 331 | 19 | public function pbkdf2($algo, $password, $salt, $iterations, $length = 0) |
|
| 379 | |||
| 380 | /** |
||
| 381 | * Prefixes data with a keyed hash value so that it can later be detected if it is tampered. |
||
| 382 | * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]] |
||
| 383 | * as those methods perform the task. |
||
| 384 | * @param string $data the data to be protected |
||
| 385 | * @param string $key the secret key to be used for generating hash. Should be a secure |
||
| 386 | * cryptographic key. |
||
| 387 | * @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase |
||
| 388 | * hex digits will be generated. |
||
| 389 | * @return string the data prefixed with the keyed hash |
||
| 390 | * @throws InvalidConfigException when HMAC generation fails. |
||
| 391 | * @see validateData() |
||
| 392 | * @see generateRandomKey() |
||
| 393 | * @see hkdf() |
||
| 394 | * @see pbkdf2() |
||
| 395 | */ |
||
| 396 | 3 | public function hashData($data, $key, $rawHash = false) |
|
| 405 | |||
| 406 | /** |
||
| 407 | * Validates if the given data is tampered. |
||
| 408 | * @param string $data the data to be validated. The data must be previously |
||
| 409 | * generated by [[hashData()]]. |
||
| 410 | * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]]. |
||
| 411 | * function to see the supported hashing algorithms on your system. This must be the same |
||
| 412 | * as the value passed to [[hashData()]] when generating the hash for the data. |
||
| 413 | * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]]. |
||
| 414 | * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists |
||
| 415 | * of lowercase hex digits only. |
||
| 416 | * hex digits will be generated. |
||
| 417 | * @return string|false the real data with the hash stripped off. False if the data is tampered. |
||
| 418 | * @throws InvalidConfigException when HMAC generation fails. |
||
| 419 | * @see hashData() |
||
| 420 | */ |
||
| 421 | 21 | public function validateData($data, $key, $rawHash = false) |
|
| 441 | |||
| 442 | private $_useLibreSSL; |
||
| 443 | private $_randomFile; |
||
| 444 | |||
| 445 | /** |
||
| 446 | * Generates specified number of random bytes. |
||
| 447 | * Note that output may not be ASCII. |
||
| 448 | * @see generateRandomString() if you need a string. |
||
| 449 | * |
||
| 450 | * @param int $length the number of bytes to generate |
||
| 451 | * @return string the generated random bytes |
||
| 452 | * @throws InvalidParamException if wrong length is specified |
||
| 453 | * @throws Exception on failure. |
||
| 454 | */ |
||
| 455 | 69 | public function generateRandomKey($length = 32) |
|
| 556 | |||
| 557 | /** |
||
| 558 | * Generates a random string of specified length. |
||
| 559 | * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding. |
||
| 560 | * |
||
| 561 | * @param int $length the length of the key in characters |
||
| 562 | * @return string the generated random key |
||
| 563 | * @throws Exception on failure. |
||
| 564 | */ |
||
| 565 | 47 | public function generateRandomString($length = 32) |
|
| 578 | |||
| 579 | /** |
||
| 580 | * Generates a secure hash from a password and a random salt. |
||
| 581 | * |
||
| 582 | * The generated hash can be stored in database. |
||
| 583 | * Later when a password needs to be validated, the hash can be fetched and passed |
||
| 584 | * to [[validatePassword()]]. For example, |
||
| 585 | * |
||
| 586 | * ```php |
||
| 587 | * // generates the hash (usually done during user registration or when the password is changed) |
||
| 588 | * $hash = Yii::$app->getSecurity()->generatePasswordHash($password); |
||
| 589 | * // ...save $hash in database... |
||
| 590 | * |
||
| 591 | * // during login, validate if the password entered is correct using $hash fetched from database |
||
| 592 | * if (Yii::$app->getSecurity()->validatePassword($password, $hash) { |
||
| 593 | * // password is good |
||
| 594 | * } else { |
||
| 595 | * // password is bad |
||
| 596 | * } |
||
| 597 | * ``` |
||
| 598 | * |
||
| 599 | * @param string $password The password to be hashed. |
||
| 600 | * @param int $cost Cost parameter used by the Blowfish hash algorithm. |
||
| 601 | * The higher the value of cost, |
||
| 602 | * the longer it takes to generate the hash and to verify a password against it. Higher cost |
||
| 603 | * therefore slows down a brute-force attack. For best protection against brute-force attacks, |
||
| 604 | * set it to the highest value that is tolerable on production servers. The time taken to |
||
| 605 | * compute the hash doubles for every increment by one of $cost. |
||
| 606 | * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', |
||
| 607 | * the output is always 60 ASCII characters, when set to 'password_hash' the output length |
||
| 608 | * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php) |
||
| 609 | * @throws Exception on bad password parameter or cost parameter. |
||
| 610 | * @see validatePassword() |
||
| 611 | */ |
||
| 612 | 1 | public function generatePasswordHash($password, $cost = null) |
|
| 632 | |||
| 633 | /** |
||
| 634 | * Verifies a password against a hash. |
||
| 635 | * @param string $password The password to verify. |
||
| 636 | * @param string $hash The hash to verify the password against. |
||
| 637 | * @return bool whether the password is correct. |
||
| 638 | * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available. |
||
| 639 | * @see generatePasswordHash() |
||
| 640 | */ |
||
| 641 | 1 | public function validatePassword($password, $hash) |
|
| 666 | |||
| 667 | /** |
||
| 668 | * Generates a salt that can be used to generate a password hash. |
||
| 669 | * |
||
| 670 | * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function |
||
| 671 | * requires, for the Blowfish hash algorithm, a salt string in a specific format: |
||
| 672 | * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters |
||
| 673 | * from the alphabet "./0-9A-Za-z". |
||
| 674 | * |
||
| 675 | * @param int $cost the cost parameter |
||
| 676 | * @return string the random salt value. |
||
| 677 | * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31. |
||
| 678 | */ |
||
| 679 | protected function generateSalt($cost = 13) |
||
| 695 | |||
| 696 | /** |
||
| 697 | * Performs string comparison using timing attack resistant approach. |
||
| 698 | * @see http://codereview.stackexchange.com/questions/13512 |
||
| 699 | * @param string $expected string to compare. |
||
| 700 | * @param string $actual user-supplied string. |
||
| 701 | * @return bool whether strings are equal. |
||
| 702 | */ |
||
| 703 | 41 | public function compareString($expected, $actual) |
|
| 716 | |||
| 717 | /** |
||
| 718 | * Masks a token to make it uncompressible. |
||
| 719 | * Applies a random mask to the token and prepends the mask used to the result making the string always unique. |
||
| 720 | * Used to mitigate BREACH attack by randomizing how token is outputted on each request. |
||
| 721 | * @param string $token An unmasked token. |
||
| 722 | * @return string A masked token. |
||
| 723 | * @since 2.0.12 |
||
| 724 | */ |
||
| 725 | 40 | public function maskToken($token) |
|
| 731 | |||
| 732 | /** |
||
| 733 | * Unmasks a token previously masked by `maskToken`. |
||
| 734 | * @param string $maskedToken A masked token. |
||
| 735 | * @return string An unmasked token, or an empty string in case of token format is invalid. |
||
| 736 | * @since 2.0.12 |
||
| 737 | */ |
||
| 738 | 8 | public function unmaskToken($maskedToken) |
|
| 749 | } |
||
| 750 |