Create a new hosted certificate.
432192
def create(gandi, private_key, certificate, certificate_id):
    
    if not certificate and not certificate_id:
        gandi.echo('One of --certificate or --certificate-id is needed.')
        return
    if certificate and certificate_id:
        gandi.echo('Only one of --certificate or --certificate-id is needed.')

    if os.path.isfile(private_key):
        with open(private_key) as fhandle:
            private_key = fhandle.read()

    if certificate:
        if os.path.isfile(certificate):
            with open(certificate) as fhandle:
                certificate = fhandle.read()
    else:
        cert = gandi.certificate.info(certificate_id)
        certificate = gandi.certificate.pretty_format_cert(cert)

    result = gandi.hostedcert.create(private_key, certificate)

    output_keys = ['id', 'subject', 'date_created', 'date_expire',
                   'fqdns', 'vhosts']

    output_hostedcert(gandi, result, output_keys)

    return result
75955
def create(self, name, plugin_name, plugin_version,
               cluster_template_id=None, default_image_id=None,
               is_transient=None, description=None, cluster_configs=None,
               node_groups=None, user_keypair_id=None,
               anti_affinity=None, net_id=None, count=None,
               use_autoconfig=None, shares=None,
               is_public=None, is_protected=None):
        """"""

        data = {
            'name': name,
            'plugin_name': plugin_name,
            'plugin_version': plugin_version,
        }

        return self._do_create(data, cluster_template_id, default_image_id,
                               is_transient, description, cluster_configs,
                               node_groups, user_keypair_id, anti_affinity,
                               net_id, count, use_autoconfig, shares,
                               is_public, is_protected, api_ver=2)
763935
def create_transport(host, connect_timeout, ssl=False):
    """"""
    if ssl:
        return SSLTransport(host, connect_timeout, ssl)
    else:
        return TCPTransport(host, connect_timeout)
493028
def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size, vlan, ip, script, script_args, ssh):
        """"""
        from gandi.cli.modules.network import Ip, Iface
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring('vm')
            disk_name = 'sys_%s' % hostname[2:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        if ip_version:
            vm_params['ip_version'] = ip_version
            vm_params['bandwidth'] = bandwidth

        if script:
            with open(script) as fd:
                vm_params['script'] = fd.read()
            if script_args:
                vm_params['script_args'] = script_args

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            if isinstance(size, tuple):
                prefix, size = size
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        ip_summary = []
        if ip_version == 4:
            ip_summary = ['v4', 'v6']
        elif ip_version == 6:
            ip_summary = ['v6']

        if vlan:
            ip_ = None
            ip_summary.append('private')
            if ip:
                try:
                    ip_ = Ip.info(ip)
                except Exception:
                    pass
                else:
                    if not Ip._check_and_detach(ip_, None):
                        return
            if ip_:
                iface_id = ip_['iface_id']
            else:
                ip_create = Ip.create(4,
                                      vm_params['datacenter_id'],
                                      bandwidth,
                                      None,
                                      vlan,
                                      ip)

                iface_id = ip_create['iface_id']

            # if there is a public ip, will attach this one later, else give
            # the iface to vm.create
            if not ip_version:
                vm_params['iface_id'] = iface_id

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        cls.echo('* Configuration used: %d cores, %dMb memory, ip %s, '
                 'image %s, hostname: %s, datacenter: %s' %
                 (cores, memory, '+'.join(ip_summary), image, hostname,
                  datacenter))

        # background mode, bail out now (skip interactive part)
        if background and (not vlan or not ip_version):
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vlan and ip_version:
            attach = Iface._attach(iface_id, vm_id)
            if background:
                return attach

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        if vm_id and ip_version:
            cls.wait_for_sshd(vm_id)
            if ssh:
                cls.ssh_keyscan(vm_id)
                cls.ssh(vm_id, 'root', None)
315497
def create_connection():
    """"""

    global _cached_connection
    settings = oz.settings

    if settings["redis_cache_connections"] and _cached_connection != None:
        return _cached_connection
    else:
        conn = redis.StrictRedis(
            host=settings["redis_host"],
            port=settings["redis_port"],
            db=settings["redis_db"],
            password=settings["redis_password"],
            decode_responses=settings["redis_decode_responses"],
            ssl=settings["redis_use_ssl"],
            ssl_keyfile=settings["redis_ssl_keyfile"],
            ssl_certfile=settings["redis_ssl_certfile"],
            ssl_cert_reqs=settings["redis_ssl_cert_reqs"],
            ssl_ca_certs=settings["redis_ssl_ca_certs"]
        )

        if settings["redis_cache_connections"]:
            _cached_connection = conn

        return conn
1007253
def create(cls, name, value):
        
        sshkey_params = {
            'name': name,
            'value': value,
        }

        result = cls.call('hosting.ssh.create', sshkey_params)
        return result
1361748
def create(self, virtual_host):
        
        virtual_host = quote(virtual_host, '')
        return self.http_client.put(API_VIRTUAL_HOST % virtual_host)
594704
def to_cert(raw_cert)
      logger.debug "CertMunger raw_cert:\n#{raw_cert}"
      new_cert = build_cert(raw_cert)
      logger.debug "CertMunger reformatted_cert:\n#{new_cert}"
      logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert'

      OpenSSL::X509::Certificate.new new_cert
    end
575253
def sync_certificates(self, subdomains=None):
        
        result = run(".acme.sh/acme.sh --list", quiet=True)
        logger.info("Syncing Webfaction certificates")
        for acme_certificate_description in result.split('\n')[1:]:
            main_domain = acme_certificate_description.split()[0]
            if subdomains and main_domain not in subdomains:
                continue
            if exists(os.path.join("~/.acme.sh/", main_domain)):
                certificate_cer = self.get_remote_content(
                    os.path.join("~/.acme.sh/", main_domain, main_domain + ".cer")
                )
                certificate_key = self.get_remote_content(
                    os.path.join("~/.acme.sh/", main_domain, main_domain + ".key")
                )
                certificate_ca = self.get_remote_content(
                    os.path.join("~/.acme.sh/", main_domain, "ca.cer")
                )
                certificate_name = self.slugify(main_domain)

                certificate = self._certificates.get(certificate_name)
                if (certificate is None
                    or certificate['certificate'] != certificate_cer
                    or certificate['private_key'] != certificate_key
                    or certificate['intermediates'] != certificate_ca):
                    new_certificate = dict(
                        name=certificate_name,
                        certificate=certificate_cer,
                        private_key=certificate_key,
                        intermediates=certificate_ca,
                    )
                    if certificate is None:
                        logger.info("Creating new certificate for %s" % main_domain)
                        self.api.create_certificate(new_certificate)
                    else:
                        logger.info("Updating certificate for %s" % main_domain)
                        self.api.update_certificate(new_certificate)
                    self._certificates[certificate_name] = new_certificate
178983
public static X509Certificate newClientCertificate(X509Metadata clientMetadata,
                                                       PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
        try {
            KeyPair pair = newKeyPair();

            X500Name userDN = buildDistinguishedName(clientMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            // create a new certificate signed by the Fathom CA certificate
            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    clientMetadata.notBefore,
                    clientMetadata.notAfter,
                    userDN,
                    pair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
            certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
            certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
            certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
            if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) {
                GeneralNames subjectAltName = new GeneralNames(
                        new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);

            X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
            PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
            bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                    extUtils.createSubjectKeyIdentifier(pair.getPublic()));

            // confirm the validity of the user certificate
            userCert.checkValidity();
            userCert.verify(caCert.getPublicKey());
            userCert.getIssuerDN().equals(caCert.getSubjectDN());

            // verify user certificate chain
            verifyChain(userCert, caCert);

            targetFolder.mkdirs();

            // save certificate, stamped with unique name
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String id = date;
            File certFile = new File(targetFolder, id + ".cer");
            int count = 0;
            while (certFile.exists()) {
                id = date + "_" + Character.toString((char) (0x61 + count));
                certFile = new File(targetFolder, id + ".cer");
                count++;
            }

            // save user private key, user certificate and CA certificate to a PKCS#12 store
            File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
            if (p12File.exists()) {
                p12File.delete();
            }
            KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
            userStore.setKeyEntry(MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[]{userCert});
            userStore.setCertificateEntry(MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
            saveKeyStore(p12File, userStore, clientMetadata.password);

            // save user private key, user certificate, and CA certificate to a PEM store
            File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
            if (pemFile.exists()) {
                pemFile.delete();
            }
            PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile));
            pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(), new SecureRandom());
            pemWriter.writeObject(userCert);
            pemWriter.writeObject(caCert);
            pemWriter.flush();
            pemWriter.close();

            // save certificate after successfully creating the key stores
            saveCertificate(userCert, certFile);

            // update serial number in metadata object
            clientMetadata.serialNumber = userCert.getSerialNumber().toString();

            return userCert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate client certificate!", t);
        }
    }
261453
def create(gandi, address, destination):
    """"""
    source, domain = address

    result = gandi.forward.create(domain, source, destination)

    return result
638680
def create(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    conn.create_topic(name)
    log.info('Created SNS topic %s', name)
    _invalidate_cache()
    return True
1041425
def create_remote(self, name, url, **kwargs):
        """"""
        return Remote.create(self, name, url, **kwargs)
764155
def install_cert(selfsigned):
    """"""

    _check_root()

    if selfsigned:
        log('Generating self signed (insecure) certificate/key '
            'combination')

        try:
            os.mkdir('/etc/ssl/certs/hfos')
        except FileExistsError:
            pass
        except PermissionError:
            log("Need root (e.g. via sudo) to generate ssl certificate")
            sys.exit(1)

        def create_self_signed_cert():
            """Create a simple self signed SSL certificate"""

            # create a key pair
            k = crypto.PKey()
            k.generate_key(crypto.TYPE_RSA, 1024)

            if os.path.exists(cert_file):
                try:
                    certificate = open(cert_file, "rb").read()
                    old_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                       certificate)
                    serial = old_cert.get_serial_number() + 1
                except (crypto.Error, OSError) as e:
                    log('Could not read old certificate to increment '
                        'serial:', type(e), e, exc=True, lvl=warn)
                    serial = 1
            else:
                serial = 1

            # create a self-signed certificate
            certificate = crypto.X509()
            certificate.get_subject().C = "DE"
            certificate.get_subject().ST = "Berlin"
            certificate.get_subject().L = "Berlin"
            # noinspection PyPep8
            certificate.get_subject().O = "Hackerfleet"
            certificate.get_subject().OU = "Hackerfleet"
            certificate.get_subject().CN = gethostname()
            certificate.set_serial_number(serial)
            certificate.gmtime_adj_notBefore(0)
            certificate.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
            certificate.set_issuer(certificate.get_subject())
            certificate.set_pubkey(k)
            certificate.sign(k, b'sha512')

            open(key_file, "wt").write(str(
                crypto.dump_privatekey(crypto.FILETYPE_PEM, k),
                encoding="ASCII"))

            open(cert_file, "wt").write(str(
                crypto.dump_certificate(crypto.FILETYPE_PEM, certificate),
                encoding="ASCII"))

            open(combined_file, "wt").write(str(
                crypto.dump_certificate(crypto.FILETYPE_PEM, certificate),
                encoding="ASCII") + str(
                crypto.dump_privatekey(crypto.FILETYPE_PEM, k),
                encoding="ASCII"))

        create_self_signed_cert()

        log('Done: Install Cert')
    else:

        # TODO

        log('Not implemented yet. You can build your own certificate and '
            'store it in /etc/ssl/certs/hfos/server-cert.pem - it should '
            'be a certificate with key, as this is used server side and '
            'there is no way to enter a separate key.', lvl=error)
1269131
function newClientStub() {
    // First create the appropriate TLS certs with dgraph cert:
    //     $ dgraph cert
    //     $ dgraph cert -n localhost
    //     $ dgraph cert -c user
    const rootCaCert = fs.readFileSync(path.join(__dirname, 'tls', 'ca.crt'));
    const clientCertKey = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.key'));
    const clientCert = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.crt'));
    return new dgraph.DgraphClientStub(
        "localhost:9080",
        grpc.credentials.createSsl(rootCaCert, clientCertKey, clientCert));
}
680511
def create_csr(key_file, organization_name, common_name, serial_number, file_):
    """"""
    key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_file.read())

    req = crypto.X509Req()
    subj = req.get_subject()

    subj.O = organization_name  # noqa: E741 (we can't do anything about this)
    subj.CN = common_name
    subj.serialNumber = serial_number

    req.set_pubkey(key)
    req.sign(key, 'md5')

    file_.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, req))
722720
def create_repository(self):
        """"""
        repo = repository.Repository(
            self.repository_config['repository'],
            self.username,
            self.password,
            self.disable_progress_bar
        )
        repo.set_certificate_authority(self.cacert)
        repo.set_client_certificate(self.client_cert)
        return repo