private function encryptPrivateKey(PKEncryptionEnabledUserInterface $user)
    {
        if (!$user->isPrivateKeyEncrypted()) {
            $privateKey = $user->getPrivateKey();
            $passwordDigest = $this->getUserPasswordDigest($user);

            if ($passwordDigest) {
                $iv = $this->cryptographyProvider->generateIV(CryptographyProviderInterface::PRIVATE_KEY_ENCRYPTION);

                $keyData = new KeyData($passwordDigest, $iv);
                try {
                    $encryptedPrivateKey = $this->cryptographyProvider->encrypt(
                                    $privateKey,
                                    $keyData,
                                    CryptographyProviderInterface::PRIVATE_KEY_ENCRYPTION);

                    $encrypted = true;
                }
                catch (\Exception $ex) {
                    $encryptedPrivateKey = $privateKey;
                    $iv = null;
                    $encrypted = false;
                }
            }
            else {
                $encryptedPrivateKey = $privateKey;
                $iv = null;
                $encrypted = false;
            }

            $user->setPrivateKey($encryptedPrivateKey);
            if ($encrypted) {
                $user->setPrivateKeyIv($iv);
                $user->setPrivateKeyEncrypted(true);
            }
        }
    }