Extracts the public key and saves it to a file.

@param string      $file       The file path.
@param string      $private    The private key.
@param null|string $passphrase The passphrase.

@throws RuntimeException If the file could not be written.

@api
179401
public function extractPublicKeyToFile($file, $private, $passphrase = null)
    {
        $public = $this->extractPublicKey($private, $passphrase);

        if (false === @ file_put_contents($file, $public)) {
            $error = error_get_last();

            throw new RuntimeException(sprintf(
                'The public key file "%s" could not be written: %s',
                $file,
                $error['message']
            ));
        }
    }
954457
public static function createFromKeyFile(string $file, ?string $password = null, array $additional_values = []): JWK
    {
        $values = KeyConverter::loadFromKeyFile($file, $password);
        $values = \array_merge($values, $additional_values);

        return JWK::create($values);
    }
440913
private function getFileKey(\SplFileInfo $file)
    {
        $key = null;

        if ($h = @fopen($file, 'r')) {
            rawurldecode(rtrim(fgets($h)));
            $value = stream_get_contents($h);
            fclose($h);
            $key = substr($value, 0, strpos($value, "\n"));
        }

        return $key;
    }
1075508
public function copyToAppliedDir($file)
    {
        if (false === @copy($file->getPathName(), $this->appliedFilesDir . '/' . $file->getFileName())) {
            throw new RuntimeException('cannot copy the sql file to applied directory. check the <info>'. $this->appliedFilesDir . '</info> directory.');
        }
    }
159813
public function store($public_key_file, $private_key_file)
    {
        file_put_contents($public_key_file, $this->public_key_text);
        file_put_contents($private_key_file, $this->private_key_text);
        chmod($private_key_file, 0600);

        return $this;
    }
338400
public function signStream($stream, $privateKey)
    {
        try {
            $virgilSourceStream = new VirgilStreamDataSource($stream);
            $virgilSourceStream->reset();

            return (new CryptoVirgilStreamSigner($this->hashAlgorithm))->sign(
                $virgilSourceStream,
                $privateKey
            );
        } catch (Exception $exception) {
            throw new ContentSigningException($exception->getMessage(), $exception->getCode());
        }
    }
702067
public function loadKey($type)
    {
        if (!in_array($type, [self::TYPE_PUBLIC, self::TYPE_PRIVATE])) {
            throw new \InvalidArgumentException(sprintf('The key type must be "public" or "private", "%s" given.', $type));
        }

        $rawKey = file_get_contents($this->getKeyPath($type));
        $key    = call_user_func_array("openssl_pkey_get_$type", self::TYPE_PRIVATE == $type ? [$rawKey, $this->getPassphrase()] : [$rawKey]);

        if (!$key) {
            $sslError = '';
            while ($msg = trim(openssl_error_string(), " \n\r\t\0\x0B\"")) {
                if ('error:' === substr($msg, 0, 6)) {
                    $msg = substr($msg, 6);
                }
                $sslError .= "\n $msg";
            }

            throw new \RuntimeException(
                sprintf('Failed to load %s key: %s', $type, $sslError)
            );
        }

        return $key;
    }
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
226037
public function addPrivateKey(PrivateKeyInterface $privateKey)
    {
        $pubKeyHex = $privateKey->getPublicKey()->getHex();
        $this->privateKeys[$pubKeyHex] = $privateKey;
    }
782109
public function loadPrivateKey(PrivateKeyConfiguration $key) : PrivateKey
    {
        if ($key->isFile()) {
            $privateKey = File::getFileContents($key->getFilePath());
        } else {
            $privateKey = $key->getContents();
        }

        return PrivateKey::create($privateKey, $key->getPassPhrase());
    }
791997
protected function generatePublicKey($path, $passphrase)
    {
        $processArgs = sprintf('rsa -pubout -in %s/private.pem -out %s/public.pem -passin pass:%s', $path, $path, $passphrase);

        $this->generateKey($processArgs);
    }
63575
protected function getPrivateKey()
    {
        if (empty($this->options['private_key_path'])) {
            throw new \RuntimeException('Missing private_key_path for generate a DKIM signature.');
        }

        if (!is_readable($this->options['private_key_path'])) {
            throw new \RuntimeException(sprintf('Private key file does not exists or is not readable: %s', $this->options['private_key_path']));
        }

        $privateKey = file_get_contents($this->options['private_key_path']);

        if (false === $privateKey) {
            throw new \RuntimeException(sprintf('Can\'t read private key in file %s', $this->options['private_key_path']));
        }

        return $privateKey;
    }
577593
public static function deleteIdentity($privateKeyFile) {
        if (!is_file($privateKeyFile)) {
            throw new \Exception('Private key file not found.');
        }
        exec('ssh-add -L | grep '. $privateKeyFile, $output);
        $tmpFile = tempnam(sys_get_temp_dir(), 'publickey_');
        file_put_contents($tmpFile, end($output));
        exec('ssh-add -d ' . $tmpFile . ' >/dev/null 2>&1', $output);
        unlink($tmpFile);
    }
119454
public static function sign(string $message, string $passphrase): self
    {
        $keys = PrivateKey::fromPassphrase($passphrase);

        return static::new([
            'publickey' => $keys->getPublicKey()->getHex(),
            'signature' => $keys->sign(Hash::sha256(new Buffer($message)))->getBuffer()->getHex(),
            'message'   => $message,
        ]);
    }
222743
private PrivateKey loadPrivateKey(File privateKeyFile)
    throws Exception
    {
    // Load the key file.
    System.out.println("Loading private key from "
               + privateKeyFile
               + ", using " + providerClassName
               + " as the private key loading provider");
        FileInputStream privateKeyInputStream = null;
        byte[] keyBytes;
        
        try
        {
            privateKeyInputStream = new FileInputStream(privateKeyFile);
            keyBytes = new byte[(int) privateKeyFile.length()];
            privateKeyInputStream.read(keyBytes);
        }
        finally
        {
            IO.close(privateKeyInputStream);
        }
    
        // Dynamically register the Bouncy Castle provider for RSA
    // support.
    Class providerClass = Loader.loadClass(this.getClass(),providerClassName);
    Provider provider = (Provider)providerClass.newInstance();
    Security.insertProviderAt(provider, 1);
    try {
        // Load the private key
        PKCS8EncodedKeySpec privateKeySpec
        = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory
        = KeyFactory.getInstance("RSA");
        PrivateKey privateKey
        = keyFactory.generatePrivate(privateKeySpec);
        
        System.out.println("Loaded " + privateKey.getAlgorithm()
                   + " " + privateKey.getFormat()
                   + " private key.");
        return privateKey;
    } finally {
        // Dynamically deinstall the RSA provider 
        Security.removeProvider(provider.getName());
    }
    }
490426
public function export(string $password = NULL): string {
        $status = openssl_pkey_export(
            $this->getHandle(),
            $output,
            $password
        );
        if(!$status) {
            throw new RuntimeException(OpenSSL::getLastError());
        }
        return $output;
    }
630363
public InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream);
    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
    InputStream clear;

    try {
      clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(
          new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
              .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));

      JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);

      return new LazyMaterializeDecryptorInputStream(pgpFact);
    } catch (PGPException e) {
      throw new IOException(e);
    }
  }