Generate the keys we need for a GRR server.
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
1346884
def generate_secret_key():
    """"""
    import string
    import random

    rng = random.SystemRandom()
    return ''.join(
        rng.choice(string.ascii_letters + string.digits)
        for dummy in range(0, 256)
    )
599584
private ResultSet generateKeysResultSet(final UpdateResult res) {
        if (this.generatedKeysColumnIndexes == null &&
            this.generatedKeysColumnNames == null) {

            return res.generatedKeys.resultSet().withStatement(this);
        } else if (this.generatedKeysColumnIndexes != null) {
            return res.generatedKeys.resultSet().withStatement(this).
                withProjection(this.generatedKeysColumnIndexes);

        } else {
            return res.generatedKeys.resultSet().withStatement(this).
                withProjection(this.generatedKeysColumnNames);
        }
    }
1119267
def gen_hyper_keys(minion_id,
                   country='US',
                   state='Utah',
                   locality='Salt Lake City',
                   organization='Salted',
                   expiration_days='365'):
    '''
    
    '''
    key_dir = os.path.join(
            __opts__['pki_dir'],
            'libvirt')
    if not os.path.isdir(key_dir):
        os.makedirs(key_dir)
    cakey = os.path.join(key_dir, 'cakey.pem')
    cacert = os.path.join(key_dir, 'cacert.pem')
    cainfo = os.path.join(key_dir, 'ca.info')
    if not os.path.isfile(cainfo):
        with salt.utils.files.fopen(cainfo, 'w+') as fp_:
            fp_.write('cn = salted\nca\ncert_signing_key')
    if not os.path.isfile(cakey):
        subprocess.call(
                'certtool --generate-privkey > {0}'.format(cakey),
                shell=True)
    if not os.path.isfile(cacert):
        cmd = ('certtool --generate-self-signed --load-privkey {0} '
               '--template {1} --outfile {2}').format(cakey, cainfo, cacert)
        subprocess.call(cmd, shell=True)
    sub_dir = os.path.join(key_dir, minion_id)
    if not os.path.isdir(sub_dir):
        os.makedirs(sub_dir)
    priv = os.path.join(sub_dir, 'serverkey.pem')
    cert = os.path.join(sub_dir, 'servercert.pem')
    srvinfo = os.path.join(sub_dir, 'server.info')
    cpriv = os.path.join(sub_dir, 'clientkey.pem')
    ccert = os.path.join(sub_dir, 'clientcert.pem')
    clientinfo = os.path.join(sub_dir, 'client.info')
    if not os.path.isfile(srvinfo):
        with salt.utils.files.fopen(srvinfo, 'w+') as fp_:
            infodat = salt.utils.stringutils.to_str(
                'organization = salted\ncn = {0}\ntls_www_server'
                '\nencryption_key\nsigning_key'
                '\ndigitalSignature\nexpiration_days = {1}'.format(
                   __grains__['fqdn'], expiration_days
                )
            )
            fp_.write(infodat)
    if not os.path.isfile(priv):
        subprocess.call(
                'certtool --generate-privkey > {0}'.format(priv),
                shell=True)
    if not os.path.isfile(cert):
        cmd = ('certtool --generate-certificate --load-privkey {0} '
               '--load-ca-certificate {1} --load-ca-privkey {2} '
               '--template {3} --outfile {4}'
               ).format(priv, cacert, cakey, srvinfo, cert)
        subprocess.call(cmd, shell=True)
    if not os.path.isfile(clientinfo):
        with salt.utils.files.fopen(clientinfo, 'w+') as fp_:
            infodat = salt.utils.stringutils.to_str(
                'country = {0}\nstate = {1}\nlocality = {2}\n'
                'organization = {3}\ncn = {4}\n'
                'tls_www_client\nencryption_key\nsigning_key\n'
                'digitalSignature'.format(
                    country,
                    state,
                    locality,
                    organization,
                    __grains__['fqdn']
                )
            )
            fp_.write(infodat)
    if not os.path.isfile(cpriv):
        subprocess.call(
                'certtool --generate-privkey > {0}'.format(cpriv),
                shell=True)
    if not os.path.isfile(ccert):
        cmd = ('certtool --generate-certificate --load-privkey {0} '
               '--load-ca-certificate {1} --load-ca-privkey {2} '
               '--template {3} --outfile {4}'
               ).format(cpriv, cacert, cakey, clientinfo, ccert)
        subprocess.call(cmd, shell=True)
776194
def add_key(pub):
    """"""
    global _server_keys
    key = rsa.PublicKey.load_pkcs1(pub)
    _server_keys[_compute_fingerprint(key)] = key
558023
def keys(self):
        """"""
        keys = Struct.keys(self)
        for key in (
                '_cloud_provider',
                '_naming_policy',
                '_setup_provider',
                'known_hosts_file',
                'repository',
        ):
            if key in keys:
                keys.remove(key)
        return keys
1103328
def fillkeys(Recs):
    
    keylist, OutRecs = [], []
    for rec in Recs:
        for key in list(rec.keys()):
            if key not in keylist:
                keylist.append(key)
    for rec in Recs:
        for key in keylist:
            if key not in list(rec.keys()):
                rec[key] = ""
        OutRecs.append(rec)
    return OutRecs, keylist
1042053
def generate_key(self):
        
        req = self.request(self.uri + "/keys")
        private_key = req.post().json()
        return private_key['priv']
1315701
function generateKeyPair (pub, prv) {
  try {
    mkdirp.sync(path.dirname(pub))
    mkdirp.sync(path.dirname(prv))

    childProcess.execFileSync('openssl', [
      'genrsa',
      '-out',
      prv,
      '4096'
    ], {
      stdio: 'ignore'
    })

    childProcess.execFileSync('openssl', [
      'rsa',
      '-pubout',
      '-in',
      prv,
      '-out',
      pub
    ], {
      stdio: 'ignore'
    })
  } catch (e) {
    throw new Error(
      'Failed to generate keys using OpenSSL. Please ensure you have OpenSSL ' +
      'installed and configured on your system.'
    )
  }
}
1156696
def keys(self) -> Iterator[str]:
        """"""
        if self.param:
            yield self.param_name
        yield from self.paths.keys()
487301
def keys(self):
        
        return GramGenerator(self.path, self.elem, keys=True,
                             ignore_hash=self.ignore_hash)
891560
def generate_key(self):
        
        sql = self.sql()
        key, created = self.get_or_create_model_key()
        if created:
            db_table = self.model._meta.db_table
            logger.debug('created new key {0} for model {1}'.format(key, db_table))
            model_cache_info = ModelCacheInfo(db_table, key)
            model_cache_backend.share_model_cache_info(model_cache_info)
        query_key = u'{model_key}{qs}{db}'.format(model_key=key,
                                                  qs=sql,
                                                  db=self.db)
        key = hashlib.md5(query_key.encode('utf-8')).hexdigest()
        return key
56739
def gen_key(path):
    '''
    
    '''
    cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path)
    if not os.path.isdir(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    subprocess.call(cmd, shell=True)
1156449
def make_pkey(key_type=crypto.TYPE_RSA, key_bits=4096):
  
  key = crypto.PKey()
  key.generate_key(key_type, key_bits)
  return key
585221
def GenerateDPKGFiles(self, template_path):
    """"""

    # Rename the generated binaries to the correct name.
    template_binary_dir = os.path.join(template_path, "dist/debian/grr-client")
    package_name = config.CONFIG.Get(
        "ClientBuilder.package_name", context=self.context)
    target_binary_dir = os.path.join(
        template_path, "dist/debian/%s%s" %
        (package_name,
         config.CONFIG.Get("ClientBuilder.target_dir", context=self.context)))
    if package_name == "grr-client":
      # Need to rename the template path or the move will fail.
      shutil.move(template_binary_dir, "%s-template" % template_binary_dir)
      template_binary_dir = "%s-template" % template_binary_dir

    utils.EnsureDirExists(os.path.dirname(target_binary_dir))
    shutil.move(template_binary_dir, target_binary_dir)

    shutil.move(
        os.path.join(target_binary_dir, "grr-client"),
        os.path.join(
            target_binary_dir,
            config.CONFIG.Get("Client.binary_name", context=self.context)))

    deb_in_dir = os.path.join(template_path, "dist/debian/debian.in/")

    self.GenerateDirectory(deb_in_dir, os.path.join(
        template_path, "dist/debian"), [("grr-client", package_name)])

    # Generate directories for the /usr/sbin link.
    utils.EnsureDirExists(
        os.path.join(template_path, "dist/debian/%s/usr/sbin" % package_name))

    if config.CONFIG.Get("Client.fleetspeak_enabled", context=self.context):
      self._GenerateFleetspeakConfig(template_path)
      shutil.rmtree(deb_in_dir)
      shutil.rmtree(os.path.join(template_path, "dist", "fleetspeak"))
      return

    # Generate the nanny template. This only exists from client version 3.1.2.5
    # onwards.
    if config.CONFIG["Template.version_numeric"] >= 3125:
      self.GenerateFile(
          os.path.join(target_binary_dir, "nanny.sh.in"),
          os.path.join(target_binary_dir, "nanny.sh"))

    # Generate the upstart template.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/upstart.in/grr-client.conf"),
        os.path.join(template_path, "dist/debian/%s.upstart" % package_name))

    # Generate the initd template. The init will not run if it detects upstart
    # is present.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/initd.in/grr-client"),
        os.path.join(template_path, "dist/debian/%s.init" % package_name))

    # Generate the systemd unit file.
    self.GenerateFile(
        os.path.join(template_path,
                     "dist/debian/systemd.in/grr-client.service"),
        os.path.join(template_path, "dist/debian/%s.service" % package_name))

    # Clean up the template dirs.
    shutil.rmtree(deb_in_dir)
    shutil.rmtree(os.path.join(template_path, "dist/debian/upstart.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/initd.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/systemd.in"))
682405
private function generatePKIKeys()
    {
        // OPENSSL config
        $config = array(
            'digest_alg' => $this->settings['private_key']['digest_method'],
            'private_key_bits' => $this->settings['private_key']['bits'],
            'private_key_type' => $this->settings['private_key']['type'],
        );

        $privateKey = null;
        $resource = openssl_pkey_new($config);

        openssl_pkey_export($resource, $privateKey);

        if(!$privateKey) {
            throw new EncryptionException('Private key could not be generated');
        }

        $publicKeyDetails = openssl_pkey_get_details($resource);
        $publicKey = $publicKeyDetails['key'];

        return array($publicKey, $privateKey);
    }
785992
def RecurseKeys(self):
    
    root_key = self.GetRootKey()
    if root_key:
      for registry_key in root_key.RecurseKeys():
        yield registry_key