Generate the SP metadata XML file

@param Connect $connect
@param string  $privateKey
@param array   $data

@return MessageResponse
977952
protected function generateXml(Connect $connect, $privateKey, $data)
    {
        $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey);

        $certificate = new X509Certificate();
        $certificate->loadPem($certificateGen);

        $builder = new MetadataBuilder();
        $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate);

        $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile();
        file_put_contents($path, $xml);

        $message = (new SpEntityConfigurationMessage())
            ->setXml($xml);

        $message = (new SignedMessageDecorator($message))
            ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey))
            ->sign($privateKey);

        $certificate = $connect->getSaml()
            ->getMetadata()
            ->getFirstIdpSsoDescriptor()
            ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION)
            ->getCertificate()
            ->toPem();

        return (new MessageResponse($message))->buildEncrypted($certificate);
    }
641462
public function build($aConnection, $isDevMode = true)
    {
        Type::addType('file_id', FileIdType::class);

        return EntityManager::create(
            $aConnection,
            Setup::createYAMLMetadataConfiguration([__DIR__ . '/Mapping'], $isDevMode)
        );
    }
867615
public function create(Connect $connect)
    {
        $tokenRequest = $this->getTokenizer()->signTokenRequest(
            $this->getTokenizer()->createTokenRequest(
                $connect->getUser(),
                $connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID()
            ),
            $connect->getSaml()->getPrivateKey()
        );

        $request = (new RequestDescriptor())
            ->setUrl($this->buildUrl('/api/token'))
            ->setMethod('POST');
        $request->setBodyParams(['token-request' => json_encode($tokenRequest->toArray())]);

        try {
            return json_decode($this->send($request)->getBody(), true);
        } catch (\Exception $e) {
            $previous = $e->getPrevious();

            if ($previous instanceof BadResponseException) {
                $error = json_decode($previous->getResponse()->getBody(true), true);

                throw new TokenException($error['error'], $error['code'], $previous);
            }

            throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious());
        }
    }
322447
private static function buildRelationships(array $data): MapInterface
    {
        $relationships = new Map('int', Relationship::class);

        foreach ($data as $response) {
            foreach ($response['graph']['relationships'] as $rel) {
                $relationships = $relationships->put(
                    (int) $rel['id'],
                    new Relationship\Relationship(
                        new Id((int) $rel['id']),
                        new Type($rel['type']),
                        new Id((int) $rel['startNode']),
                        new Id((int) $rel['endNode']),
                        self::buildProperties($rel['properties'])
                    )
                );
            }
        }

        return $relationships;
    }
438657
public static function encryptRsaPrivate(string $data, string $privateKey, string $format = null): string
    {
        $key = \openssl_pkey_get_private($privateKey);

        $encrypted = '';
        if (!\openssl_private_encrypt($data, $encrypted, $key, OPENSSL_PKCS1_OAEP_PADDING)) {
            throw new CryptoException('RSA private encrypt error: ' . openssl_error_string());
        }
        \openssl_pkey_free($key);

        return self::fromRaw($encrypted, $format);
    }
1339984
public function exportPrivateKey(VirgilPrivateKey $privateKey, $password = '')
    {
        try {
            return $this->cryptoService->privateKeyToDer($privateKey->getValue(), $password);
        } catch (Exception $exception) {
            throw new VirgilCryptoException($exception->getMessage());
        }
    }
1231528
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
                      key_spec=None, grant_tokens=None, region=None, key=None,
                      keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        data_key = conn.generate_data_key(
            key_id,
            encryption_context=encryption_context,
            number_of_bytes=number_of_bytes,
            key_spec=key_spec,
            grant_tokens=grant_tokens
        )
        r['data_key'] = data_key
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
887693
public function sign($data_to_sign)
    {
        // Get the private key resource from the private key data
        $private_key = openssl_pkey_get_private($this->private_key_text);
        if ($private_key === false) {
            return;
        }

        // Create the base64 encoded copy of the signature.
        $signature = '';
        if (! openssl_sign($data_to_sign, $signature, $private_key, OPENSSL_ALGO_SHA256)) {
            return;
        }
        $base64_signature = base64_encode($signature);

        return $base64_signature;
    }
466890
private function generateSocketConnection(Connect $connection): bool
    {
        $this->logger->debug('Creating socket connection');
        $this->connectionParameters = $connection->getConnectionParameters();
        $this->socket = stream_socket_client(
            $this->connectionParameters->getConnectionUrl(),
            $errorCode,
            $errorDescription,
            60,
            STREAM_CLIENT_CONNECT
        );

        $this
            ->checkForConnectionErrors($errorCode, $errorDescription)
            ->setSocketTimeout();

        $this->logger->debug('Created socket connection successfully, continuing', stream_get_meta_data($this->socket));
        return true;
    }
659980
public function onGatewayMessage($connection, $data)
    {
        $cmd = $data['cmd'];
        if ($cmd === GatewayProtocol::CMD_PING) {
            return;
        }
        // 上下文数据
        Context::$client_ip     = $data['client_ip'];
        Context::$client_port   = $data['client_port'];
        Context::$local_ip      = $data['local_ip'];
        Context::$local_port    = $data['local_port'];
        Context::$connection_id = $data['connection_id'];
        Context::$client_id     = Context::addressToClientId($data['local_ip'], $data['local_port'],
            $data['connection_id']);
        // $_SERVER 变量
        $_SERVER = array(
            'REMOTE_ADDR'       => long2ip($data['client_ip']),
            'REMOTE_PORT'       => $data['client_port'],
            'GATEWAY_ADDR'      => long2ip($data['local_ip']),
            'GATEWAY_PORT'      => $data['gateway_port'],
            'GATEWAY_CLIENT_ID' => Context::$client_id,
        );
        // 检查session版本，如果是过期的session数据则拉取最新的数据
        if ($cmd !== GatewayProtocol::CMD_ON_CLOSE && isset($this->_sessionVersion[Context::$client_id]) && $this->_sessionVersion[Context::$client_id] !== crc32($data['ext_data'])) {
            $_SESSION = Context::$old_session = \GatewayWorker\Lib\Gateway::getSession(Context::$client_id);
        } else {
            if (!isset($this->_sessionVersion[Context::$client_id])) {
                $this->_sessionVersion[Context::$client_id] = crc32($data['ext_data']);
            }
            // 尝试解析 session
            if ($data['ext_data'] != '') {
                Context::$old_session = $_SESSION = Context::sessionDecode($data['ext_data']);
            } else {
                Context::$old_session = $_SESSION = null;
            }
        }

        if ($this->processTimeout) {
            pcntl_alarm($this->processTimeout);
        }
        // 尝试执行 Event::onConnection、Event::onMessage、Event::onClose
        switch ($cmd) {
            case GatewayProtocol::CMD_ON_CONNECTION:
                if ($this->_eventOnConnect) {
                    call_user_func($this->_eventOnConnect, Context::$client_id);
                }
                break;
            case GatewayProtocol::CMD_ON_MESSAGE:
                if ($this->_eventOnMessage) {
                    call_user_func($this->_eventOnMessage, Context::$client_id, $data['body']);
                }
                break;
            case GatewayProtocol::CMD_ON_CLOSE:
                unset($this->_sessionVersion[Context::$client_id]);
                if ($this->_eventOnClose) {
                    call_user_func($this->_eventOnClose, Context::$client_id);
                }
                break;
        }
        if ($this->processTimeout) {
            pcntl_alarm(0);
        }
        
        // session 必须是数组
        if ($_SESSION !== null && !is_array($_SESSION)) {
            throw new \Exception('$_SESSION must be an array. But $_SESSION=' . var_export($_SESSION, true) . ' is not array.');
        }

        // 判断 session 是否被更改
        if ($_SESSION !== Context::$old_session && $cmd !== GatewayProtocol::CMD_ON_CLOSE) {
            $session_str_now = $_SESSION !== null ? Context::sessionEncode($_SESSION) : '';
            \GatewayWorker\Lib\Gateway::setSocketSession(Context::$client_id, $session_str_now);
            $this->_sessionVersion[Context::$client_id] = crc32($session_str_now);
        }

        Context::clear();
    }
749945
public function editPublicKey($publicKey, $privateKey) {
        $this->validatePublicKeyName($publicKey);

        return $this->getCommand('EditPublicKey', array(
            'properties' => json_encode(array('privateKey' => $privateKey)),
            'publicKey' => $publicKey,
        ))->execute();
    }
991964
public static function decryptRsaPublic(string $data, string $publicKey, string $format = null): string
    {
        $data = self::toRaw($data, $format);
        $key = \openssl_pkey_get_public($publicKey);

        $decrypted = '';
        if (!\openssl_public_decrypt($data, $decrypted, $key, OPENSSL_PKCS1_OAEP_PADDING)) {
            throw new CryptoException('RSA public decrypt error: ' . openssl_error_string());
        }
        \openssl_pkey_free($key);

        return $decrypted;
    }
764731
public function publishMessage($message, $exchange, $routing_key = '', $flags = AMQP_NOPARAM, $attributes = [])
    {
        if (!isset($this->_exchanges[$exchange])) {
            throw new InvalidKeyException(['publish message to `:1` exchange with `:2` routing_key failed: exchange is NOT exists', $exchange, $routing_key]);
        }

        try {
            $this->_exchanges[$exchange]->publish($message, $routing_key, $flags, $attributes);
        } catch (\Exception $e) {
            throw new AmqpException(['publish message to `:1` exchange with `:2` routing_key failed: `:3`', $exchange, $routing_key, $e->getMessage()]);
        }

        return $this;
    }
367073
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = [])
    {
        if (isset($params['dbname'])) {
            $dbName = $this->getDbNameFromEnv($params['dbname']);
        } else {
            $dbName = $this->getDbNameFromEnv($params['master']['dbname']);
        }

        if ('pdo_sqlite' === $params['driver']) {
            if (isset($params['path'])) {
                $params['path'] = str_replace('__DBNAME__', $dbName, $params['path']);
            }

            if (isset($params['master']['path'])) {
                $params['master']['path'] = str_replace('__DBNAME__', $dbName, $params['master']['path']);
            }

            if (!empty($params['slaves'])) {
                foreach ($params['slaves'] as &$slave) {
                    $slave['path'] = str_replace('__DBNAME__', $dbName, $slave['path']);
                }
            }
        } else {
            $params['dbname'] = $dbName;
        }

        return parent::createConnection($params, $config, $eventManager, $mappingTypes);
    }
1374318
public static function createRSAKey(int $size, array $values = []): JWK
    {
        if (0 !== $size % 8) {
            throw new \InvalidArgumentException('Invalid key size.');
        }

        if (384 > $size) {
            throw new \InvalidArgumentException('Key length is too short. It needs to be at least 384 bits.');
        }

        $key = \openssl_pkey_new([
            'private_key_bits' => $size,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]);
        \openssl_pkey_export($key, $out);
        $rsa = RSAKey::createFromPEM($out);
        $values = \array_merge(
            $values,
            $rsa->toArray()
        );

        return JWK::create($values);
    }
439368
protected function readPrivateKey(SplFileObject $privateKey)
    {
        $key = '';
        while (!$privateKey->eof()) {
            $key .= $privateKey->fgets();
        }
        return $key;
    }
24715
public function setConnect(array $connect): void
    {
        $this->connect = array_merge($this->connect, $connect);
        $this->checkConnect();
    }