Migrate Annotation Encrypted to Encryption

@param SymfonyStyle $helper

@return bool
329966
private function migrateAnnotationEncryption(SymfonyStyle $helper)
    {
        $helper->note('The encrypted annotation uses mcrypt and therefore is deprecated. This migration will identify all entities using the old annotation, decrpyting with the old method and encrypt the value for the encryption annotation. After execution you have to replace the annotation.');

        /** @var \ReflectionProperty[] $todo */
        $todo = [];
        $classesWithoutNewAnnotation = [];

        $annotationsReader = $this->getContainer()->get('annotations.reader');

        /* Get entites */
        $classes = DoctrineHelper::getAllEntityClassNames($this->getDoctrineManager());
        $helper->comment(sprintf('Found %d entities', count($classes)));

        /* Search for annotation */
        foreach ($classes as $className) {
            $properties = DoctrineHelper::getPropertiesByAnnotation($className, Encrypted::class, $annotationsReader);

            if (0 < count($properties)) {
                $todo[$className] = $properties;
            }
        }

        if (0 === count($todo)) {
            $helper->success('Nothing to do.');

            return true;
        }

        $helper->comment(sprintf('%d entities use the encrypted annotation', count($todo)));

        /* Disable Listener */
        $subscriber = DoctrineHelper::getEventListener(EncryptionSubscriber::class, $this->getDoctrineManager());
        if (null === $subscriber) {
            throw new \LogicException('Event Subscriber not found.');
        }

        $this->getDoctrineManager()->getEventManager()->removeEventSubscriber($subscriber);

        $secret = $this->getContainer()->getParameter('pm__tool.configuration.doctrine.encryption');
        $helper->comment(sprintf('Secret: %s', $secret));

        $secretKey = substr(hash('sha256', $secret), 1, 32);

        /* Get Values */
        foreach ($todo as $className => $properties) {
            $helper->section($className);

            $tableHeader = [
                '#',
            ];
            /** @var \ReflectionProperty $property */
            foreach ($properties as $property) {
                $tableHeader[] = $property->getName();

                if (false === DoctrineHelper::hasPropertyAnnotation($property, Encryption::class, $annotationsReader) && false === in_array($className, $classesWithoutNewAnnotation)) {
                    $classesWithoutNewAnnotation[] = $className;
                }
            }

            $tableValues = [];

            $entites = $this->getDoctrine()->getRepository($className)->findAll();
            foreach ($entites as $entity) {
                $tableRow = [
                    $entity->getId(),
                ];

                foreach ($properties as $property) {
                    $tableRow[] = CryptUtility::decrypt($property->getValue($entity), $secretKey);
                }

                $tableValues[] = $tableRow;
            }

            $helper->table($tableHeader, $tableValues);
        }

        /* Warnings for missing new annotation */
        if (0 < count($classesWithoutNewAnnotation)) {
            $helper->warning(
                array_merge(
                    [
                        'The following classes have properties without the new annotation:',
                    ],
                    $classesWithoutNewAnnotation
                )
            );
        }

        /* Are you sure? */
        if (false === $helper->confirm('Are you sure to reencrypt the shown values?', false)) {
            $helper->warning('Cancelled');

            return false;
        }

        /* Encrypt values */
        foreach ($todo as $className => $properties) {
            $entites = $this->getDoctrine()->getRepository($className)->findAll();
            foreach ($entites as $entity) {

                foreach ($properties as $property) {
                    /** @var Encryption|null $annotation */
                    $annotation = DoctrineHelper::getPropertyAnnotation($property, Encryption::class, $annotationsReader);
                    if (null === $annotation) {
                        $cipher = OpenSSLHelper::CIPHER_AES_256_CBC;
                    } else {
                        $cipher = $annotation->cipher;
                    }

                    $value = CryptUtility::decrypt($property->getValue($entity), $secretKey);

                    $property->setValue($entity, OpenSSLHelper::encrypt($value, $secretKey, $cipher));
                }

                $this->getDoctrineManager()->persist($entity);
            }
        }

        $this->getDoctrineManager()->flush();

        $helper->success('Values changed. Please remove the old annotations now.');

        return true;
    }
196518
protected function getHelper($helper, $params=array())
    {
        if ($this->isLibraryHelper($helper)) $this->_helperClassName = $this->_libNamespace . $helper;
        else if ($this->isApplicationHelper($helper)) $this->_helperClassName = $this->_appNamespace . $helper;
        else throw new HelperNotFoundException('The helper ' . $helper . ' does not exist');

        $this->_helperParams = $params;
    }
1246126
private function getContentEncryptionAlgorithm(array $complete_headers)
    {
        $content_encryption_algorithm = $this->getJWAManager()->getAlgorithm($complete_headers['enc']);
        Assertion::isInstanceOf($content_encryption_algorithm, Algorithm\ContentEncryptionAlgorithmInterface::class, sprintf('The key encryption algorithm "%s" is not supported or does not implement ContentEncryptionInterface.', $complete_headers['enc']));

        return $content_encryption_algorithm;
    }
417960
public function validationDefault(Validator $validator)
    {
        $validator
            ->add('id', 'valid', ['rule' => 'numeric'])
            ->allowEmpty('id', 'create');

        $validator
            ->add('email', 'valid', ['rule' => 'email'])
            ->notEmpty('email');

        $validator
            ->notEmpty('password');

        $validator
            ->allowEmpty('new_password');


        $validator
            ->allowEmpty('confirm_password');

        $validator
            ->add('new_password', 'custom', [
                'rule' => function ($value, $context) {
                    if (!array_key_exists('confirm_password', $context['data'])) {
                        return false;
                    }
                    if ($value !== $context['data']['confirm_password']) {
                        return false;
                    }
                    return true;
                },
                'message' => __d('CakeAdmin', 'Passwords are not equal.')]);

        $validator
            ->add('confirm_password', 'custom', ['rule' => function ($value, $context) {
                if (!array_key_exists('new_password', $context['data'])) {
                    return false;
                }
                if ($value !== $context['data']['new_password']) {
                    return false;
                }
                return true;
            },
                'message' => __d('CakeAdmin', 'Passwords are not equal.')]);

        return $validator;
    }
700251
protected function encrypt($token)
    {
        // Serialize the token object
        $token = serialize($token);
        
        // Encrypt the token if there is an Encrypter instance
        if ($this->encrypter instanceof Encrypter) {
            $token = $this->encrypter->encrypt($token);
        }
        
        // Return the token
        return $token;
    }
967485
private function getKeyEncryptionAlgorithm(array $complete_headers)
    {
        $this->log(LogLevel::DEBUG, 'Trying to find key encryption algorithm');
        $key_encryption_algorithm = $this->getJWAManager()->getAlgorithm($complete_headers['alg']);
        if (!$key_encryption_algorithm instanceof KeyEncryptionAlgorithmInterface) {
            $exception = new \InvalidArgumentException(sprintf('The key encryption algorithm "%s" is not supported or does not implement KeyEncryptionAlgorithmInterface.', $complete_headers['alg']));
            $this->log(LogLevel::ERROR, 'The key encryption algorithm {alg} is not supported or does not implement KeyEncryptionAlgorithmInterface.', ['alg' => $complete_headers['alg'], 'exception' => $exception]);
            throw $exception;
        }

        $this->log(LogLevel::DEBUG, 'Key encryption algorithm {algorithm} found', ['algorithm' => $complete_headers['alg'], 'service' > $key_encryption_algorithm]);

        return $key_encryption_algorithm;
    }
501447
public function decryptResponse($response)
    {
        if (!is_string($response)) {
            return $response;
        }

        if ($this->usesEncryption()) {
            return json_decode(
                json_encode(
                    JWT::decode(
                        $response,
                        $this->encryptionKey,
                        array($this->encryptionAlgorithm)
                    )
                ),
                true
            );
        }

        throw EncryptionConfigurationException::undeterminedEncryption();
    }
275148
public function setHelperPluginManager($helpers)
    {
        if (is_string($helpers)) {
            if (!class_exists($helpers)) {
                throw new Exception\InvalidArgumentException(sprintf(
                    'Invalid helper helpers class provided (%s)',
                    $helpers
                ));
            }
            $helpers = new $helpers();
        }
        if (!$helpers instanceof HelperPluginManager) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Helper helpers must extend Zend\View\HelperPluginManager; got type "%s" instead',
                (is_object($helpers) ? get_class($helpers) : gettype($helpers))
            ));
        }
        $helpers->setRenderer($this);
        $this->__helpers = $helpers;

        return $this;
    }
423770
public function createHelper($helper, array $config = array())
    {
        if(is_string($helper) && strpos($helper, '.') === false )
        {
            $identifier = $this->getIdentifier()->toArray();
            $identifier['name'] = $helper;
        }
        else $identifier = $helper;

        //Create the template helper
        $helper = $this->getObject($identifier, $config);

        //Check the helper interface
        if (!($helper instanceof TemplateHelperInterface))
        {
            throw new \UnexpectedValueException(
                "Template helper $identifier does not implement TemplateHelperInterface"
            );
        }

        return $helper;
    }
396030
public function postLoad($args)
    {
        $entity = $args->getEntity();

        if (false === ($entity instanceof HasEncryptedFieldsEntityInterface) && false === ($entity instanceof EncryptedEntityInterface)) {
            return false;
        }

        $properties = $this->getEntityEncryptionReflectionProperties($entity);
        foreach ($properties as $property) {
            $fieldValue = $property->getValue($entity);

            if (null === $fieldValue || true === empty($fieldValue)) {
                continue;
            }

            /** @var Encryption $annotation */
            $annotation = DoctrineHelper::getPropertyAnnotation($property, Encryption::class, $this->getReader());

            $property->setValue($entity, OpenSSLHelper::decrypt($fieldValue, $this->getEncryptionKey(), $annotation->cipher));
        }

        /*
         * Deprecated usage
         */
        if (0 === count($properties)) {
            foreach ($this->getEntityEncryptedReflectionProperties($entity) as $property) {
                $fieldValue = $property->getValue($entity);

                if (null === $fieldValue || true === empty($fieldValue)) {
                    continue;
                }

                $property->setValue($entity, CryptUtility::decrypt($fieldValue, $this->getEncryptionKey()));
            }
        }

        return true;
    }
1164855
private function add_helpers( $helpers ) {
		foreach( $helpers as $helper ) {
			$helper = $this->validate_helper_input( $helper );
			if ( is_array( $helper ) ) {
				$this->add_helper( $helper );
			}

		}

	}
1338799
public function hasHelper($helperType)
    {
        if ($this->isValidKey($helperType)) {
            if (!is_null($formHelperMap = $this->getHelperMap()->get($helperType))
                && count($formHelperMap) > 0
            ) {
                return true;
            }
        } else {
            throw new InvalidArgumentException('Invalid form helper type given');
        }
        return false;
    }
214323
public static function encode($value, $key = false)
	{
		$key ? static::$crypter->setKey($key) : static::$crypter->setKey(static::safe_b64decode(static::$config['crypto_key']));
		static::$crypter->setIV(static::safe_b64decode(static::$config['crypto_iv']));

		$value = static::$crypter->encrypt($value);
		return static::safe_b64encode(static::add_hmac($value));

	}
1309952
protected static function getEncrypter()
	{
		static $crypt;

		if (!$crypt)
		{
			$key = \App::get('session')->getFormToken();

			$crypt = new Encrypter(
				new Simple,
				new Key('simple', $key, $key)
			);
		}

		return $crypt;
	}
301416
public static function md5()
    {
        // Helper Class Exists
        if (isset(self::$ChecksumHelper)) {
            return self::$ChecksumHelper;
        }
        // Initialize Class
        self::$ChecksumHelper = new ChecksumHelper();
        // Return Helper Class
        return self::$ChecksumHelper;
    }
127218
public function isPerUserEncryptionEnabled()
    {
        $perUserEncryptionEnabled = false;

        if ($this->settings['per_user_encryption_enabled']) {
            $encryptionMetadata = $this->metadataFactory->getAllMetadata();
            /** @var ClassMetadata $classEncryptionMetadata */
            foreach ($encryptionMetadata as $classEncryptionMetadata) {
                if (self::MODE_PER_USER_SHAREABLE === $classEncryptionMetadata->encryptionMode) {
                    $perUserEncryptionEnabled = true;
                    break;
                }
            }
        }

        return $perUserEncryptionEnabled;
    }
283673
private function getContentEncryptionAlgorithm(array $complete_headers)
    {
        $this->log(LogLevel::DEBUG, 'Trying to find content encryption algorithm');
        $content_encryption_algorithm = $this->getJWAManager()->getAlgorithm($complete_headers['enc']);
        if (!$content_encryption_algorithm instanceof ContentEncryptionAlgorithmInterface) {
            $exception = new \InvalidArgumentException(sprintf('The key encryption algorithm "%s" is not supported or does not implement ContentEncryptionInterface.', $complete_headers['enc']));
            $this->log(LogLevel::ERROR, 'The key encryption algorithm {alg} is not supported or does not implement ContentEncryptionInterface.', ['alg' => $complete_headers['enc'], 'exception' => $exception]);
            throw $exception;
        }

        $this->log(LogLevel::DEBUG, 'Content encryption algorithm {algorithm} found', ['algorithm' => $complete_headers['enc'], 'service' > $content_encryption_algorithm]);

        return $content_encryption_algorithm;
    }