Create a new Crypto Key File

@return void
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();

    }
142764
def create_key_file(service, key):
    """"""
    keyfile = _keyfile_path(service)
    if os.path.exists(keyfile):
        log('Keyfile exists at %s.' % keyfile, level=WARNING)
        return

    with open(keyfile, 'w') as fd:
        fd.write(key)

    log('Created new keyfile at %s.' % keyfile, level=INFO)
273056
protected static function generateRandomKey()
  {
    $chars = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
    $baseKey = '';
    for ($i = 0; $i < self::$baseKeyLength; $i++) {
      $baseKey .= $chars[rand(0, count($chars) - 1)];
    }
    $baseKey .= uniqid();

    return $baseKey;
  }
246877
public function createBackup()
    {
        $this->output->outputLine();

        if ( !file_exists($this->createFilePath([$this->localBackupTarget, 'key'])) ) {
            $this->output->outputLine('<b>You don\'t have a keyfile!</b>');
            $this->output->outputLine();
            $this->output->outputLine('Call \'./flow backup:key\' to to generate it.');
            $this->output->outputLine();
            return;
        }

        $this->output->outputLine('<b>Prepare Backup</b>');
        $this->output->outputLine();

        $this->emitBackupStarted();
        $newVersion = time();

        $stats = array(
            'checked' => 0,
            'added' => 0,
            'updated' => 0,
            'removed' => 0,
        );

        $this->collectSystemSettings();

        $this->dumpDatabase();

        foreach ($this->backupFolders as $folderIndex => $folder) {
            $relativeFolder = $this->getPathByFlowRoot($folder);

            $this->output->outputLine('<b>'.($folderIndex+1).'/'.count($this->backupFolders).' Backup '.$relativeFolder.'</b>');
            $this->output->outputLine();
            $this->output->outputLine('Load Backup Versions..');

            $latestFlatBackup = $this->getFlatBackup($folder);
            $newBackupClean = $this->getBackupActions($folder, $newVersion, $latestFlatBackup);
            $stats['checked'] = $stats['checked'] + count($latestFlatBackup);

            if ( count($newBackupClean)>0 ) {
                // encrypt and create backup..
                $this->files->createDirectoryRecursively($this->createDirectoryPath([$this->localBackupTarget, $newVersion, $relativeFolder]));
                $this->output->outputLine('Backup Files..');
                $this->output->progressStart(count($newBackupClean));
                $i = 0;
                foreach ($newBackupClean as $sha1 => $fileItem) {
                    if ($fileItem['action'] == 'add' || $fileItem['action'] == 'update') {
                        if ($fileItem['action'] == 'add') {
                            $stats['added']++;
                        } else {
                            $stats['updated']++;
                        }

                        $this->cryptService->encryptFileToFile(
                            $this->createFilePath([FLOW_PATH_ROOT, $fileItem['file']]),
                            $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.file']));
                        file_put_contents(
                            $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.meta']),
                            json_encode($fileItem));

                    } else {
                        if ($fileItem['action'] == 'remove') {
                            $stats['removed']++;

                            file_put_contents(
                                $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.meta']),
                                json_encode($fileItem));
                        }
                    }
                    $i++;
                    $this->output->progressSet($i);
                }
                $this->output->progressFinish();
                $this->output->outputLine();
            }
        }

        if ( file_exists($this->createDirectoryPath([$this->localBackupTarget, $newVersion])) ) {
            $this->meta['version'] = $newVersion;
            $now = new \DateTime();
            $this->meta['timestamp'] = $now->getTimestamp();
            $this->meta['stats'] = $stats;
            file_put_contents($this->createFilePath([$this->localBackupTarget, $newVersion, 'info.meta']),
                json_encode($this->meta, JSON_PRETTY_PRINT));
        }

        $this->deleteTempFolders();

        $this->removeOldBackups();

        $this->output->outputLine('<b>Backup Finished</b>');
        $this->output->outputLine(' - Checked: '.$stats['checked']);
        $this->output->outputLine(' - Added:   '.$stats['added']);
        $this->output->outputLine(' - Updated: '.$stats['updated']);
        $this->output->outputLine(' - Removed: '.$stats['removed']);
        $this->output->outputLine();
        $this->emitBackupFinished($this->output, $stats);
        return;
    }
333623
public static function generateSecretKey()
    {
        // make parameters file if not exists
        touch(self::getRootDir().'/config/parameters.yml');

        /* @var $manipulator Parameters */
        $manipulator = self::getContainer()->getManipulator('parameters');
        if (!$manipulator->get('secret')) {
            $manipulator->set('secret', SecretKey::generate());
        }
    }
712419
protected void createKeystore() {

		java.security.cert.Certificate signingCert = null;
		PrivateKey  caPrivKey  = null;

		if(_caCert == null || _caPrivKey == null)
		{
			try
			{
				log.debug("Keystore or signing cert & keypair not found.  Generating...");

				KeyPair caKeypair = getRSAKeyPair();
				caPrivKey = caKeypair.getPrivate();
				signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

				log.debug("Done generating signing cert");
				log.debug(signingCert);

				_ks.load(null, _keystorepass);

				_ks.setCertificateEntry(_caCertAlias, signingCert);
				_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});

				File caKsFile = new File(root, _caPrivateKeystore);

				OutputStream os = new FileOutputStream(caKsFile);
				_ks.store(os, _keystorepass);

				log.debug("Wrote JKS keystore to: " +
						caKsFile.getAbsolutePath());

				// also export a .cer that can be imported as a trusted root
				// to disable all warning dialogs for interception

				File signingCertFile = new File(root, EXPORTED_CERT_NAME);

				FileOutputStream cerOut = new FileOutputStream(signingCertFile);

				byte[] buf = signingCert.getEncoded();

				log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

				cerOut.write(buf);
				cerOut.flush();
				cerOut.close();

				_caCert = (X509Certificate)signingCert;
				_caPrivKey  = caPrivKey;
			}
			catch(Exception e)
			{
				log.error("Fatal error creating/storing keystore or signing cert.", e);
				throw new Error(e);
			}
		}
		else
		{
			log.debug("Successfully loaded keystore.");
			log.debug(_caCert);

		}

	}
732111
public function createBackup()
    {
        try {
            // compressor instance
            $compressor = new Compress('backup-' . date('Y-m-d_H-i-s'), $this->backupConfig->TempPath);

            // first we need to export all the databases
            $backupMongo = new BackupMongo($this->backupConfig->get('MongoDatabases', [], true), $this->backupConfig->TempPath);
            $compressor->addSources($backupMongo->exportDatabases());

            // add folders to the compressor
            $compressor->addSources($this->backupConfig->get('Folders', [], true));

            // compress all the folders and database exports in one archive
            $backupArchive = $compressor->compress();

            // encrypt the archive -> only if passpharse is set
            $encryptionStatus = false;
            if ($this->backupConfig->get('Encryption', false)) {
                $encryption = new Encrypt($backupArchive, $this->backupConfig->Encryption, $this->backupConfig->TempPath);
                $encArchive = $encryption->encrypt();
                $encryptionStatus = true;
            } else {
                $encArchive = $backupArchive;
            }

            $backupSize = filesize($encArchive);

            // check if we should backup to S3
            if ($this->backupConfig->get('S3', false)) {
                $s3 = new Lib\S3($this->backupConfig->get('S3'));

                // move the old 1-day backup to 2-day backup
                $oldBackup = $s3->moveOldBackup();
                $this->backupsCreated['s3']['48h'] = [
                    'filename'  => $oldBackup,
                    'encrypted' => $encryptionStatus
                ];
                

                // create new 1 day backup
                $uploadedFile = $s3->upload($encArchive, 'backup-1day-old');
                $this->backupsCreated['s3']['24h'] = [
                    'size'      => $backupSize,
                    'filename'  => $uploadedFile,
                    'encrypted' => $encryptionStatus
                ];

                // check if we need 7-day backup and 30-day backup
                $frequencies = $this->backupConfig->get('Frequency', [], true);

                // week
                // we always do weekly backups on sunday
                if (in_array('Week', $frequencies) && date('w') == '0') {
                    $s3->deleteBackup('backup-week');
                    $copiedFile = $s3->copyLatestBackup('backup-week');
                    $this->backupsCreated['s3']['weekly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // month
                // we always do monthly backups on the last day of the month
                if (in_array('Month', $frequencies) && date('d') == date('t')) {
                    $s3->deleteBackup('backup-month');
                    $copiedFile = $s3->copyLatestBackup('backup-month');
                    $this->backupsCreated['s3']['monthly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // year
                // we always do monthly backups on the last day of the year
                if (in_array('Year', $frequencies) && date('d.m') == '31.12') {
                    $s3->deleteBackup('backup-year');
                    $copiedFile = $s3->copyLatestBackup('backup-year');
                    $this->backupsCreated['s3']['yearly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }
            }

            // check if a file system backup is required
            if ($this->backupConfig->get('BackupStoragePath', false)) {
                $fsBackup = new Lib\Filesystem($this->backupConfig->get('BackupStoragePath'));

                // move the old 1-day backup to 2-day backup
                $oldBackup = $fsBackup->moveOldBackup();
                $this->backupsCreated['local']['48h'] = [
                    'filename'  => $oldBackup,
                    'encrypted' => $encryptionStatus
                ];

                // create new 1 day backup
                $uploadedFile = $fsBackup->upload($encArchive, 'backup-1day-old');
                $this->backupsCreated['local']['24h'] = [
                    'size'      => $backupSize,
                    'filename'  => $uploadedFile,
                    'encrypted' => $encryptionStatus
                ];

                // check if we need 7-day backup and 30-day backup
                $frequencies = $this->backupConfig->get('Frequency', [], true);

                // week
                // we always do weekly backups on sunday
                if (in_array('Week', $frequencies) && date('w') == '0') {
                    $fsBackup->deleteBackup('backup-week');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-week');
                    $this->backupsCreated['local']['weekly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // month
                // we always do monthly backups on the last day of the month
                if (in_array('Month', $frequencies) && date('d') == date('t')) {
                    $fsBackup->deleteBackup('backup-month');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-month');
                    $this->backupsCreated['local']['monthly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // year
                // we always do monthly backups on the last day of the year
                if (in_array('Year', $frequencies) && date('d.m') == '31.12') {
                    $fsBackup->deleteBackup('backup-year');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-year');
                    $this->backupsCreated['local']['yearly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }
            }

            // do the cleanup
            Cleanup::doCleanup();

            // end log
            self::$log->msg('Backup ended');
            self::$log->msg('Execution time: ' . $this->getExecutionTime());

            // set success flag
            $this->isSuccessful = true;

            if ($this->storeLog) {
                self::$log->writeLog();
            } else {
                return self::$log->getLog();
            }

        } catch (\Exception $e) {
            // set success flag
            $this->isSuccessful = false;

            self::$log->msg('ERROR: ' . $e->getMessage());
            if ($this->storeLog) {
                self::$log->writeLog();
            } else {
                return self::$log->getLog();
            }
        }
    }
875410
protected function createFile()
    {
        $event = new FileEvent([
            'realPath' => $this->iterator->current(),
            'relativePath' => $this->iterator->getRelativePath()
        ]);

        $this->module->trigger(Module::EVENT_PROCESS_FILE, $event);

        $this->file = $event;
    }
265912
public function generate(): string
    {
        try {
            return DefuseKey::createNewRandomKey()->saveToAsciiSafeString();
        } catch(EnvironmentIsBrokenException $e) {
            throw new CryptoException($e->getMessage(), $e->getCode(), $e);
        }
    }
591528
public static function generateKeypair() : Keypair
    {
        try {
            $keypair = \sodium_crypto_box_keypair();
            return new Keypair(
                \sodium_crypto_box_secretkey($keypair),
                \sodium_crypto_box_publickey($keypair)
            );
        } catch (SodiumException $e) {
            throw new Exception($e->getMessage());
        }
    }
113767
public function createRequest()
    {
        $this->crt = new SignedCertificate();
        $this->crt->setPrivateKey(openssl_pkey_new($this->certConfigure));

        $privKey = $this->crt->getPrivateKey();
        $this->crt->setCsr(openssl_csr_new($this->domainName()->get(), $privKey, $this->certConfigure));

        $request = json_encode([
            'csr' => $this->crt->getCsr()
        ]);

        // Send CSR to server and wait for signing
        $response = $this->signWithServer($request);
        $response = json_decode($response);
        $this->crt->setSignedCert(openssl_x509_read($response->certificate));

        return $this;
    }
618452
public static function generateKey()
    {
        do {
            $salt = sha1(time() . mt_rand());
            $newKey = substr($salt, 0, 40);
        } // Already in the DB? Fail. Try again
        while (self::keyExists($newKey));

        return $newKey;
    }
235996
public function login_key()
	{
		//TODO: add location for pub/private key files
		return ssh2_auth_pubkey_file($this->_conn_link, $this->_config['pub_key'], $this->_config['private_key'], $this->_config['passphrase']);
	}
522157
function createSigningRequest($url, $keyPath, $csrPath, $confPath)
    {
        $this->cli->runAsUser(sprintf(
            'openssl req -new -key "%s" -out "%s" -subj "/C=/ST=/O=/localityName=/commonName=%s/organizationalUnitName=/emailAddress=%s%s/" -config "%s"',
            $keyPath, $csrPath, $url, $url, '@laravel.valet', $confPath
        ));
    }
1244704
public function create()
	{	
		$blog_dir = getcwd() . '/' . $this->name . '/';
		$this->createBlogDirectory($blog_dir);
		$this->createConfigFile($blog_dir);
		$this->createTemplateFile($blog_dir);
	}
810410
public function generateRandomApiKey()
    {
        $this->_api_key_private = md5($this->_id . uniqid());

        $this->_api_key_public = $this->generateApiPublicKey();

        return $this;
    }
314744
def write_new_key
      File.open(full_key_path, 'w') do |f|
        f.write OpenSSL::PKey::RSA.generate(1024).export()
      end
    end