Create and write the RSA private file

@throws \Exception
10347
public function createRSAPrivateKey()
    {
        $path = $this->getConfig()->getPrivateKeyFilePath();
        $this->createDir($path);
        $this->getConfig()->setPrivateKey((new RsaKeyGen())->createPrivateKey());

        if (@file_put_contents($path, $this->getConfig()->getPrivateKey()) === false) {
            throw new \Exception('Error when writing the RSA private key');
        }
    }
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()));
    }
199170
public function generateKeyFile()
    {
        $this->output->outputLine();

        if ( file_exists($this->createFilePath([$this->localBackupTarget, 'key'])) ) {
            $this->output->outputLine('<b>You have already a keyfile!</b>');
            $this->output->outputLine('If you generate a new one, all existing Backups are worthless.');
            $this->output->outputLine();
            $this->output->outputLine('Call \'./flow backup:clear --force\' to delete all Backups and the Keyfile.');
            $this->output->outputLine();
            return;
        }

        $this->output->outputLine('<b>Generate a new Crypto Key</b>');
        $this->output->outputLine();

        $this->files->createDirectoryRecursively($this->localBackupTarget);

        try {
            $key = \Crypto::createNewRandomKey();
            file_put_contents($this->createFilePath([$this->localBackupTarget, 'key']), $key);
            // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
            // they may leak the key to the attacker through side channels.
        } catch (Ex\CryptoTestFailedException $ex) {
            die('Cannot safely create a key');
        } catch (Ex\CannotPerformOperationException $ex) {
            die('Cannot safely create a key');
        }

        $this->output->outputLine('done');
        $this->output->outputLine();

    }
283302
def create_key(file_):
    
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    file_.flush()
725677
protected function writeToIPCSegment()
    {
        if (shmop_read($this->internalSemaphoreKey, 1, 1) === 1) {
            return;
        }

        $serialized_IPC_array = serialize($this->internalIPCArray);
        $shm_bytes_written = shmop_write($this->internalIPCKey, $serialized_IPC_array, 0);

        if ($shm_bytes_written !== strlen($serialized_IPC_array)) {
            throw new Exception(
                'Fatal exception writing SHM segment (shmop_write)'.strlen($serialized_IPC_array).
                '-'.shmop_size($this->internalIPCKey)
            );
        }
    }
466170
private function save()
    {
        $encodedContent = gzencode(json_encode($this->content));

        if (!file_exists($this->file)) {
            touch($this->file);
        }

        $fh = fopen($this->file, 'r+');

        if (flock($fh, LOCK_EX)) {
            ftruncate($fh, 0);
            fwrite($fh, $encodedContent);
            fflush($fh);
            flock($fh, LOCK_UN);
            fclose($fh);
        } else {
            throw new \Exception('Could not acquire exclusive file lock.');
        }
    }
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());
    }
    }
788052
private function generatePrivateECKey(): JWK
    {
        return JWKFactory::createFromKeyFile($this->privateKeyPath, $this->privateKeySecret, [
            'kid' => $this->keyId,
            'alg' => 'ES512',
            'use' => 'sig'
        ]);
    }
53203
protected function save()
    {
        if (false === ($result = @file_put_contents($this->getFilename(), $this->token))) {
            throw new \Exception(sprintf('Token could not be saved to "%s"', $this->getFilename()));
        }
    }
727553
public function create_lockfile($contents=null) {
		if(!$this->is_lockfile_present()) {
			$retval = $this->fsObj->create_file($this->get_lockfile());
			
			if(!is_null($contents)) {
				$this->fsObj->write($contents);
			}
		}
		else {
			throw new exception(__METHOD__ .": lockfile (". $this->lockFile .") already present");
		}
		
		return($retval);
	}
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;
    }
510262
public function generate() {
        $strong = false;
        $i = 0;

        while (!$strong && $this->maxTries > $i++) {
            $data = openssl_random_pseudo_bytes(32, $strong);
        }

        if (!$strong) {
            throw new RuntimeException('Could not generate private key');
        }

        // base64_encode to get a decent ascii compatible format, and trim ending ='s.
        $key = rtrim(base64_encode($data), '=');

        // We change +/ into -_ to avoid any human confusion with paths
        return strtr($key, '+/', '-_');
    }
833632
public function getRsaPrivateKey()
    {
        if ($this->rsaPrivateKey) {
            return $this->rsaPrivateKey;
        }

        if (!file_exists($this->rsaPrivateKeyFile)) {
            throw new CredentialsException('Could not read the private key file.');
        }

        $this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents($this->rsaPrivateKeyFile));

        if (!$this->rsaPrivateKey) {
            throw new CredentialsException('Cannot access private key for signing');
        }

        return $this->rsaPrivateKey;
    }
376502
static public function generate()
    {
        if (! extension_loaded('openssl')) {
            throw new \RuntimeException("Can only generate a remote desktop certificate when OpenSSL PHP extension is installed.");
        }
        
        // Generate a new private (and public) key pair
        $config = array(
            'config' => __DIR__ . '/../Resources/config/openssl.cnf'
        );
        $privkey = openssl_pkey_new($config);
        
        // Generate a certificate signing request
        $dn = array(
            "commonName" => "AzureDistributionBundle for Symfony Tools"
        );
        $csr = openssl_csr_new($dn, $privkey, $config);
        $sscert = openssl_csr_sign($csr, null, $privkey, 365, $config);
        
        return new self($privkey, $sscert);
    }
1198110
private function generateSignature()
    {
        if (!$this->getPrivateKey()) {
            throw new \Exception('No private key given.');
        }

        $signature = '';
        openssl_sign($this->getCanonizedHeaders(), $signature, $this->getPrivateKey());

        return trim(chunk_split(base64_encode($signature), 73, ' '));
    }
836600
protected void createGoogleAppsPrivateKey() throws Exception {
        if (!isValidConfiguration()) {
            LOGGER.debug("Google Apps private key bean will not be created, because it's not configured");
            return;
        }

        val bean = new PrivateKeyFactoryBean();

        if (this.privateKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
            bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX)));
        } else if (this.privateKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
            bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.FILE_URL_PREFIX)));
        } else {
            bean.setLocation(new FileSystemResource(this.privateKeyLocation));
        }

        bean.setAlgorithm(this.keyAlgorithm);
        LOGGER.debug("Loading Google Apps private key from [{}] with key algorithm [{}]",
            bean.getLocation(), bean.getAlgorithm());
        bean.afterPropertiesSet();
        LOGGER.debug("Creating Google Apps private key instance via [{}]", this.privateKeyLocation);
        this.privateKey = bean.getObject();
    }
155859
private function zSavePemFiles($x509certdata)
    {
        if (empty($this->pathCerts)) {
            throw new Exception(
                'Não está definido o diretório para armazenar os certificados.'
            );
        }
        if (! is_dir($this->pathCerts)) {
            throw new Exception(
                'Não existe o diretório para armazenar os certificados.'
            );
        }
        //recriar os arquivos pem com o arquivo pfx
        if (! file_put_contents($this->priKeyFile, $x509certdata['pkey'])) {
            throw new Exception(
                'Falha de permissão de escrita na pasta dos certificados!!'
            );
        }
        file_put_contents($this->pubKeyFile, $x509certdata['cert']);
        file_put_contents($this->certKeyFile, $x509certdata['pkey'] . "\r\n" . $x509certdata['cert']);
    }