Set (generate) OpenSSL key.

@param string $privateKey
@throws \Exception
@return void
422968
public function setPrivateKey($privateKey)
    {
        $privateKey = <<<PKEY
-----BEGIN RSA PRIVATE KEY-----
$privateKey
-----END RSA PRIVATE KEY-----
PKEY;

        if (!$privateKey = @openssl_pkey_get_private($privateKey)) {
            throw new \Exception("Invalid private key given.");
        }

        $this->privateKey = $privateKey;
    }
1153895
private function validateKey(string $key): void
    {
        $key_pattern = $this->cache->getOptions()->getKeyPattern();

        if ($key === '') {
            throw new InvalidKeyException('An empty key is not allowed');
        } elseif (!empty($key_pattern && !preg_match($key_pattern, $key))) {
            throw new InvalidKeyException(
                sprintf('The key "%s" does not match against pattern "%s"', $key, $key_pattern)
            );
        }
    }
307389
public function setAuthKey($key)
    {
        $authKeyAttribute = $this->authKeyAttribute;
        return (is_string($authKeyAttribute) && !empty($authKeyAttribute)) ? $this->$authKeyAttribute = $key : null;
    }
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);
    }
1255056
public function encryptByPrivateKey_data($data, $privatekey = '')
	{
		$RSACrypt = new RSACrypt();

		if ($privatekey != "") {
			$RSACrypt->privkey = $privatekey;
		}
		$crypt_res = "";
		for ($i = 0; $i < ((strlen($data) - strlen($data) % 117) / 117 + 1); $i++) {
			$crypt_res = $crypt_res . ($RSACrypt->encryptByPrivateKey(mb_strcut($data, $i * 117, 117, 'utf-8')));
		}
		return $crypt_res;
	}
1010377
public function sign($key, $password = null)
    {
        OpenSslException::reset();

        if (false === extension_loaded('openssl')) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::create(
                'The "openssl" extension is not available.'
            );
            // @codeCoverageIgnoreEnd
        }

        if (false === ($resource = openssl_pkey_get_private($key, $password))) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        if (false === openssl_pkey_export($resource, $private)) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        if (false === ($details = openssl_pkey_get_details($resource))) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        $this->phar->setSignatureAlgorithm(Phar::OPENSSL, $private);

        if (false === @file_put_contents($this->file . '.pubkey', $details['key'])) {
            throw FileException::lastError();
        }
    }
685017
private function setSaltKey($key)
    {
        $this->setKey($key);

        if (!function_exists('mcrypt_create_iv')) {
            throw new \BadFunctionCallException('Mcrypt extension library not loaded');
        }

        $this->iv = mcrypt_create_iv(32);
    }
147633
protected static function rsaDecrypt($ciphertext, PrivateKey $rsaPrivateKey)
    {
        $rsa = self::getRsa(RSA::ENCRYPTION_OAEP);

        $return = $rsa->loadKey($rsaPrivateKey->getKey());
        if ($return === false) {
            throw new InvalidKeyException('Decryption failed due to invalid key');
        }

        $return = @$rsa->decrypt($ciphertext);
        if ($return === false) {
            throw new InvalidCiphertextException('Decryption failed');
        }
        return $return;
    }
1125052
public function setPrivateKey($path)
    {
        if(!file_exists($path)) {
            throw new \InvalidArgumentException('the private key file does\'t exist');
        }

        $this->privateKey = file_get_contents($path);

        return $this;
    }
1187100
private function initialize()
    {
        // generate key pair.
        $this->privateKey = $this->generator->createPrivateKey();
        $this->publicKey = $this->privateKey->getPublicKey();

        // generate salt
        $this->salt = openssl_random_pseudo_bytes(16);

        $this->publicKeyContent = hex2bin($this->serializer->serialize($this->publicKey->getPoint()));
    }
602994
public function createApplicationToken($application, $privateKey)
    {
        $tokenRequest = $this->getTokenizer()->signTokenRequest(
            $this->getTokenizer()->createApplicationTokenRequest(
                $application
            ),
            $privateKey
        );

        $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());
        }
    }
641656
public function loadKey($key, $isCert = false)
    {
        if (is_file($key)) {
            $this->key = file_get_contents($key);
        } else {
            $this->key = $key;
        }
        if ($isCert) {
            $this->key = openssl_x509_read($this->key);
            openssl_x509_export($this->key, $str_cert);
            $this->x509Certificate = $str_cert;
            $this->key = $str_cert;
        } else {
            $this->x509Certificate = null;
        }
        if ($this->cryptParams['library'] == 'openssl') {
            switch ($this->cryptParams['type']) {
                case 'public':
                    if ($isCert) {
                        /* Load the thumbprint if this is an X509 certificate. */
                        $this->X509Thumbprint = self::getRawThumbprint($this->key);
                    }
                    $this->key = openssl_get_publickey($this->key);
                    if (!$this->key) {
                        throw new Exception('Unable to extract public key');
                    }
                    break;

                case 'private':
                    $this->key = openssl_get_privatekey($this->key, $this->passphrase);
                    break;

                case'symmetric':
                    if (strlen($this->key) < $this->cryptParams['keysize']) {
                        throw new Exception('Key must contain at least 25 characters for this cipher');
                    }
                    break;

                default:
                    throw new Exception('Unknown type');
            }
        }
    }
52994
public function authenticate($publicKey, $privateKey, $secure = true)
    {
        $this->options->set('publicKey', $publicKey);
        $this->options->set('privateKey', $privateKey);

        if ($secure) {
            $this->options->set('protocol', 'https');
        }
    }
1056997
public function decrypt( $text, $privateKey ) {
		$this->resetHome();

		$privateKeyId = $this->addKey( $privateKey );
		if ( !$privateKeyId ) {
			return false;
		}

		$cipherFile = $this->homeDir->makeTempFile( 'ciphertext-', $text );
		$clearFile = $this->homeDir->makeTempFile( 'cleartext-' );

		$args = array( '--decrypt', '--output', $clearFile, $cipherFile );
		$output = $this->call( $args, $retval );
		if ( $retval ) {
			$this->logger->warning( 'GPG encrypt call returned error',
				array( 'retval' => $retval, 'output' => $output ) );
			return false;
		}

		$clearText = file_get_contents( $clearFile );
		if ( !$clearText ) {
			$this->logger->warning( 'failed to load cleartext file' );
			return false;
		}

		return $clearText;
	}
444292
protected function setKey($key): self
    {
        assert(is_resource($key) === true);

        $this->closeKey();
        $this->key = $key;

        return $this;
    }
1086171
protected function _setKeys($keys)
    {
        if (!is_array($keys)) {
            throw new Exception\InvalidArgumentException('Invalid options argument provided to filter');
        }

        foreach ($keys as $type => $key) {
            if (is_file($key) and is_readable($key)) {
                $file = fopen($key, 'r');
                $cert = fread($file, 8192);
                fclose($file);
            } else {
                $cert = $key;
                $key  = count($this->keys[$type]);
            }

            switch ($type) {
                case 'public':
                    $test = openssl_pkey_get_public($cert);
                    if ($test === false) {
                        throw new Exception\InvalidArgumentException("Public key '{$cert}' not valid");
                    }

                    openssl_free_key($test);
                    $this->keys['public'][$key] = $cert;
                    break;
                case 'private':
                    $test = openssl_pkey_get_private($cert, $this->passphrase);
                    if ($test === false) {
                        throw new Exception\InvalidArgumentException("Private key '{$cert}' not valid");
                    }

                    openssl_free_key($test);
                    $this->keys['private'][$key] = $cert;
                    break;
                case 'envelope':
                    $this->keys['envelope'][$key] = $cert;
                    break;
                default:
                    break;
            }
        }

        return $this;
    }
963304
public static function decryptRsaPrivate(string $data, string $privateKey, string $format = null): string
    {
        $data = self::toRaw($data, $format);
        $key = \openssl_pkey_get_private($privateKey);

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

        return $decrypted;
    }