Creates a new key pair for each new DigitalOcean compute resource
 After creating the key, it uploads it to DigitalOcean
763217
def setup_key_pair
      public_key, private_key = generate_key
      key_name = "foreman-#{id}#{Foreman.uuid}"
      client.create_ssh_key key_name, public_key
      KeyPair.create! :name => key_name, :compute_resource_id => id, :secret => private_key
    rescue StandardError => e
      logger.warn 'failed to generate key pair'
      logger.error e.message
      logger.error e.backtrace.join("\n")
      destroy_key_pair
      raise
    end
1168066
static public Key make(byte[] kb, byte rf) {
    if( rf == -1 ) throw new IllegalArgumentException();
    Key key = new Key(kb);
    Key key2 = H2O.getk(key); // Get the interned version, if any
    if( key2 != null ) // There is one! Return it instead
      return key2;

    // Set the cache with desired replication factor, and a fake cloud index
    H2O cloud = H2O.CLOUD; // Read once
    key._cache = build_cache(cloud._idx-1,0,0,rf);
    key.cloud_info(cloud); // Now compute & cache the real data
    return key;
  }
474130
def create(self):
        
        payload = {'type': self._type}
        if self._ddoc_id and self._ddoc_id != '':
            if isinstance(self._ddoc_id, STRTYPE):
                if self._ddoc_id.startswith('_design/'):
                    payload['ddoc'] = self._ddoc_id[8:]
                else:
                    payload['ddoc'] = self._ddoc_id
            else:
                raise CloudantArgumentError(122, self._ddoc_id)
        if self._name and self._name != '':
            if isinstance(self._name, STRTYPE):
                payload['name'] = self._name
            else:
                raise CloudantArgumentError(123, self._name)
        self._def_check()
        payload['index'] = self._def

        if self._partitioned:
            payload['partitioned'] = True

        headers = {'Content-Type': 'application/json'}
        resp = self._r_session.post(
            self.index_url,
            data=json.dumps(payload, cls=self._database.client.encoder),
            headers=headers
        )
        resp.raise_for_status()
        self._ddoc_id = response_to_json_dict(resp)['id']
        self._name = response_to_json_dict(resp)['name']
1356637
def new(cls, alias, sealed_obj, algorithm, key, key_size):
        
        timestamp = int(time.time()) * 1000

        raise NotImplementedError("Creating Secret Keys not implemented")
61696
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
        '''
        
        '''
        keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
                                                             keysize, user)
        salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
        return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
1019784
def create_key_pair(self, cert_type, bits):
        

        pkey = crypto.PKey()
        pkey.generate_key(cert_type, bits)
        return pkey
314744
def write_new_key
      File.open(full_key_path, 'w') do |f|
        f.write OpenSSL::PKey::RSA.generate(1024).export()
      end
    end
450103
function create() {
  var sha1sum = crypto.createHash('sha1');
  return { update: update, digest: digest };

  function update(data) {
    sha1sum.update(data);
  }

  function digest() {
    return sha1sum.digest('hex');
  }
}
131589
def create(self, **kwargs):
        
        self.service.create(**kwargs)

        predix.config.set_env_value(self.use_class, 'url',
                self.service.settings.data['url'])
        predix.config.set_env_value(self.use_class, 'access_key_id',
                self.service.settings.data['access_key_id'])
        predix.config.set_env_value(self.use_class, 'bucket_name',
                self.service.settings.data['bucket_name'])
        predix.config.set_env_value(self.use_class, 'host',
                self.service.settings.data['host'])
        predix.config.set_env_value(self.use_class, 'secret_access_key',
                self.service.settings.data['secret_access_key'])
1154099
def new_credentials(cls):
        """"""
        from cryptography import x509
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.x509.oid import NameOID

        key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=2048,
                                       backend=default_backend())
        key_bytes = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())

        subject = issuer = x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, u'skein-internal')])
        now = datetime.utcnow()
        cert = (x509.CertificateBuilder()
                    .subject_name(subject)
                    .issuer_name(issuer)
                    .public_key(key.public_key())
                    .serial_number(x509.random_serial_number())
                    .not_valid_before(now)
                    .not_valid_after(now + timedelta(days=365))
                    .sign(key, hashes.SHA256(), default_backend()))

        cert_bytes = cert.public_bytes(serialization.Encoding.PEM)

        return cls(cert_bytes=cert_bytes, key_bytes=key_bytes)
76735
def add_bare_metal_cloud(client, cloud, keys):
    
    title = cloud.get('title')
    provider = cloud.get('provider')
    key = cloud.get('apikey', "")
    secret = cloud.get('apisecret', "")
    tenant_name = cloud.get('tenant_name', "")
    region = cloud.get('region', "")
    apiurl = cloud.get('apiurl', "")
    compute_endpoint = cloud.get('compute_endpoint', None)
    machine_ip = cloud.get('machine_ip', None)
    machine_key = cloud.get('machine_key', None)
    machine_user = cloud.get('machine_user', None)
    machine_port = cloud.get('machine_port', None)

    if provider == "bare_metal":
        machine_ids = cloud['machines'].keys()
        bare_machine = cloud['machines'][machine_ids[0]]
        machine_hostname = bare_machine.get('dns_name', None)
        if not machine_hostname:
            machine_hostname = bare_machine['public_ips'][0]

        if not machine_ip:
            machine_ip = machine_hostname
        key = machine_hostname
        machine_name = cloud['machines'][machine_ids[0]]['name']
        machine_id = machine_ids[0]

        keypairs = keys.keys()
        for i in keypairs:
            keypair_machines = keys[i]['machines']
            if keypair_machines:
                keypair_machs = keys[i]['machines']
                for mach in keypair_machs:
                    if mach[1] == machine_id:
                        machine_key = i
                        break
            else:
                pass

    client.add_cloud(title, provider, key, secret, tenant_name=tenant_name, region=region, apiurl=apiurl,
                       machine_ip=machine_ip, machine_key=machine_key, machine_user=machine_user,
                       compute_endpoint=compute_endpoint, machine_port=machine_port)
219783
def create(cls, name, datacenter, backends, vhosts, algorithm,
               ssl_enable, zone_alter):
        
        datacenter_id_ = int(Datacenter.usable_id(datacenter))
        params = {
            'datacenter_id': datacenter_id_,
            'name': name,
            'lb': {'algorithm': algorithm},
            'override': True,
            'ssl_enable': ssl_enable,
            'zone_alter': zone_alter
        }
        if vhosts:
            params['vhosts'] = vhosts
        if backends:
            params['servers'] = backends
        try:
            result = cls.call('hosting.rproxy.create', params)
            cls.echo('Creating your webaccelerator %s' % params['name'])
            cls.display_progress(result)
            cls.echo('Your webaccelerator have been created')
            return result
        except Exception as err:
            if err.code == 580142:
                for vhost in params['vhosts']:
                    dns_entry = cls.call(
                        'hosting.rproxy.vhost.get_dns_entries',
                        {'datacenter': datacenter_id_, 'vhost': vhost})
                    txt_record = "@ 3600 IN TXT \"%s=%s\"" % (dns_entry['key'],
                                                              dns_entry['txt'])

                    cname_record = "%s 3600 IN CNAME %s" % (dns_entry['key'],
                                                            dns_entry['cname'])

                    cls.echo('The domain %s don\'t use Gandi DNS or you have'
                             ' not sufficient right to alter the zone file. '
                             'Edit your zone file adding this TXT and CNAME '
                             'record and try again :' % vhost)
                    cls.echo(txt_record)
                    cls.echo(cname_record)
                    cls.echo('\nOr add a file containing %s at :\n'
                             'http://%s/%s.txt\n' % (dns_entry['txt'],
                                                     dns_entry['domain'],
                                                     dns_entry['txt']))
                    cls.separator_line('-', 4)
            else:
                cls.echo(err)
1244357
def create_service_key(self, service_name, key_name):
        
        if self.has_key(service_name, key_name):
            logging.warning("Reusing existing service key %s" % (key_name))
            return self.get_service_key(service_name, key_name)

        body = {
            'service_instance_guid': self.get_instance_guid(service_name),
            'name': key_name
            }

        return self.api.post('/v2/service_keys', body)
33448
def gen_key(minion_id, dns_name=None, password=None, key_len=2048):
    '''
    
    '''
    keygen_type = 'RSA'

    if keygen_type == "RSA":
        if HAS_M2:
            gen = RSA.gen_key(key_len, 65537)
            private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
        else:
            gen = RSA.generate(bits=key_len)
            private_key = gen.exportKey('PEM', password)
        if dns_name is not None:
            bank = 'digicert/domains'
            cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
            try:
                data = cache.fetch(bank, dns_name)
                data['private_key'] = private_key
                data['minion_id'] = minion_id
            except TypeError:
                data = {'private_key': private_key,
                        'minion_id': minion_id}
            cache.store(bank, dns_name, data)
    return private_key
880465
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'digitalocean',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])

    kwargs = {
        'name': vm_['name'],
        'size': get_size(vm_),
        'image': get_image(vm_),
        'region': get_location(vm_),
        'ssh_keys': [],
        'tags': []
    }

    # backwards compat
    ssh_key_name = config.get_cloud_config_value(
        'ssh_key_name', vm_, __opts__, search_global=False
    )

    if ssh_key_name:
        kwargs['ssh_keys'].append(get_keyid(ssh_key_name))

    ssh_key_names = config.get_cloud_config_value(
        'ssh_key_names', vm_, __opts__, search_global=False, default=False
    )

    if ssh_key_names:
        for key in ssh_key_names.split(','):
            kwargs['ssh_keys'].append(get_keyid(key))

    key_filename = config.get_cloud_config_value(
        'ssh_key_file', vm_, __opts__, search_global=False, default=None
    )

    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined key_filename \'{0}\' does not exist'.format(
                key_filename
            )
        )

    if not __opts__.get('ssh_agent', False) and key_filename is None:
        raise SaltCloudConfigError(
            'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
            'because it does not supply a root password upon building the server.'
        )

    ssh_interface = config.get_cloud_config_value(
        'ssh_interface', vm_, __opts__, search_global=False, default='public'
    )

    if ssh_interface in ['private', 'public']:
        log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
        kwargs['ssh_interface'] = ssh_interface
    else:
        raise SaltCloudConfigError(
            "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
        )

    private_networking = config.get_cloud_config_value(
        'private_networking', vm_, __opts__, search_global=False, default=None,
    )

    if private_networking is not None:
        if not isinstance(private_networking, bool):
            raise SaltCloudConfigError("'private_networking' should be a boolean value.")
        kwargs['private_networking'] = private_networking

    if not private_networking and ssh_interface == 'private':
        raise SaltCloudConfigError(
                "The DigitalOcean driver requires ssh_interface if defined as 'private' "
                "then private_networking should be set as 'True'."
    )

    backups_enabled = config.get_cloud_config_value(
        'backups_enabled', vm_, __opts__, search_global=False, default=None,
    )

    if backups_enabled is not None:
        if not isinstance(backups_enabled, bool):
            raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
        kwargs['backups'] = backups_enabled

    ipv6 = config.get_cloud_config_value(
        'ipv6', vm_, __opts__, search_global=False, default=None,
    )

    if ipv6 is not None:
        if not isinstance(ipv6, bool):
            raise SaltCloudConfigError("'ipv6' should be a boolean value.")
        kwargs['ipv6'] = ipv6

    monitoring = config.get_cloud_config_value(
        'monitoring', vm_, __opts__, search_global=False, default=None,
    )

    if monitoring is not None:
        if not isinstance(monitoring, bool):
            raise SaltCloudConfigError("'monitoring' should be a boolean value.")
        kwargs['monitoring'] = monitoring

    kwargs['tags'] = config.get_cloud_config_value(
        'tags', vm_, __opts__, search_global=False, default=False
    )

    userdata_file = config.get_cloud_config_value(
        'userdata_file', vm_, __opts__, search_global=False, default=None
    )
    if userdata_file is not None:
        try:
            with salt.utils.files.fopen(userdata_file, 'r') as fp_:
                kwargs['user_data'] = salt.utils.cloud.userdata_template(
                    __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
                )
        except Exception as exc:
            log.exception(
                'Failed to read userdata from %s: %s', userdata_file, exc)

    create_dns_record = config.get_cloud_config_value(
        'create_dns_record', vm_, __opts__, search_global=False, default=None,
    )

    if create_dns_record:
        log.info('create_dns_record: will attempt to write DNS records')
        default_dns_domain = None
        dns_domain_name = vm_['name'].split('.')
        if len(dns_domain_name) > 2:
            log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
            default_dns_hostname = '.'.join(dns_domain_name[:-2])
            default_dns_domain = '.'.join(dns_domain_name[-2:])
        else:
            log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
            default_dns_hostname = dns_domain_name[0]

        dns_hostname = config.get_cloud_config_value(
            'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
        )
        dns_domain = config.get_cloud_config_value(
            'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
        )
        if dns_hostname and dns_domain:
            log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
            __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
                                                            name=dns_hostname,
                                                            record_type=t,
                                                            record_data=d)

            log.debug('create_dns_record: %s', __add_dns_addr__)
        else:
            log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
            raise SaltCloudConfigError(
                '\'create_dns_record\' must be a dict specifying "domain" '
                'and "hostname" or the minion name must be an FQDN.'
            )

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        ret = create_node(kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on DIGITALOCEAN\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment: %s',
            vm_['name'], exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    def __query_node_data(vm_name):
        data = show_instance(vm_name, 'action')
        if not data:
            # Trigger an error in the wait_for_ip function
            return False
        if data['networks'].get('v4'):
            for network in data['networks']['v4']:
                if network['type'] == 'public':
                    return data
        return False

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_['name'],),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    if not vm_.get('ssh_host'):
        vm_['ssh_host'] = None

    # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
    addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
    arec_map = dict(list(zip(addr_families, dns_arec_types)))
    for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
                                            for family in addr_families
                                            for net in data['networks'][family]]:
        log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
        dns_rec_type = arec_map[addr_family]
        if facing == 'public':
            if create_dns_record:
                __add_dns_addr__(dns_rec_type, ip_address)
        if facing == ssh_interface:
            if not vm_['ssh_host']:
                vm_['ssh_host'] = ip_address

    if vm_['ssh_host'] is None:
        raise SaltCloudSystemExit(
            'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
        )

    log.debug(
        'Found public IP address to use for ssh minion bootstrapping: %s',
        vm_['ssh_host']
    )

    vm_['key_filename'] = key_filename
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)
    ret.update(data)

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
264028
def create_ssh_pub_key(self, name, key):
        
        self.nova.keypairs.create(name, key)
1124840
def keys_create(gandi, fqdn, flag):
    """"""
    key_info = gandi.dns.keys_create(fqdn, int(flag))

    output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
                   'public_key', 'flags', 'tag', 'status']
    output_generic(gandi, key_info, output_keys, justify=15)
    return key_info