Generates a new Root CA certificate ...
767676
private void doGenerate() {
		if (checkExistingCertificate()) {
			// prevent overwriting
			return;
		}
		try {
			final KeyStore newrootca = SslCertificateUtils.createRootCA();
			setRootca(newrootca);
		} catch (final Exception e) {
			logger.error("Error while generating Root CA certificate", e);
		}
	}
1370806
def validate(cert, ca_name, crl_file):
    '''
    
    '''
    store = OpenSSL.crypto.X509Store()
    cert_obj = _read_cert(cert)
    if cert_obj is None:
        raise CommandExecutionError(
            'Failed to read cert from {0}, see log for details'.format(cert)
        )
    ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
    ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name))
    store.add_cert(ca_cert)
    # These flags tell OpenSSL to check the leaf as well as the
    # entire cert chain.
    X509StoreFlags = OpenSSL.crypto.X509StoreFlags
    store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
    if crl_file is None:
        crl = OpenSSL.crypto.CRL()
    else:
        with salt.utils.files.fopen(crl_file) as fhr:
            crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read())
    store.add_crl(crl)
    context = OpenSSL.crypto.X509StoreContext(store, cert_obj)
    ret = {}
    try:
        context.verify_certificate()
        ret['valid'] = True
    except OpenSSL.crypto.X509StoreContextError as e:
        ret['error'] = str(e)
        ret['error_cert'] = e.certificate
        ret['valid'] = False
    return ret
121669
def _create_ssl_context(cfg):
        
        ctx = ssl.SSLContext(cfg.ssl_version)
        ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
        ctx.verify_mode = cfg.cert_reqs
        if cfg.ca_certs:
            ctx.load_verify_locations(cfg.ca_certs)
        if cfg.ciphers:
            ctx.set_ciphers(cfg.ciphers)
        return ctx
1309844
def generate_adhoc_ssl_context():
    """"""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx
267044
public static void prepareX509Infrastructure(X509Metadata metadata, File serverKeyStore, File serverTrustStore, X509Log x509log) {
        // make the specified folder, if necessary
        File folder = serverKeyStore.getParentFile();
        folder.mkdirs();

        // Fathom CA certificate
        File caKeyStore = new File(folder, CA_KEY_STORE);
        if (!caKeyStore.exists()) {
            logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath()));
            X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
            saveCertificate(caCert, new File(caKeyStore.getParentFile(), "ca.cer"));
        }

        // Fathom CRL
        File caRevocationList = new File(folder, CA_REVOCATION_LIST);
        if (!caRevocationList.exists()) {
            logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath()));
            newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);
            x509log.log("new certificate revocation list created");
        }

        // create web SSL certificate signed by CA
        if (!serverKeyStore.exists()) {
            logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath()));
            PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
            X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
            newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);
        }

        // server certificate trust store holds trusted public certificates
        if (!serverTrustStore.exists()) {
            logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_ALIAS, serverTrustStore.getAbsolutePath()));
            X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
            addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password);
        }
    }
1254639
def _create(self, common_name, public_key_algorithm='rsa',
            signature_algorithm='rsa_sha_512', key_length=2048,
            signing_ca=None):
        
        if signing_ca is None:
            signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first()
        
        cert_auth = element_resolver(signing_ca)
        
        return ElementCreator(
            GatewayCertificate,
            exception=CertificateError,
            href=self.internal_gateway.get_relation('generate_certificate'),
            json={
                'common_name': common_name,
                'public_key_algorithm': public_key_algorithm,
                'signature_algorithm': signature_algorithm,
                'public_key_length': key_length,
                'certificate_authority_href': cert_auth})
477873
def cleanup_certificates(options)
      puts 'Cleaning up certificates...' if options[:verbose]
      AgentConfig.certs_files("*.{cert,key}").each { |f| FileUtils.rm_f(f) } # requires that root_dir already known in AgentConfig
    end
1132504
def exportCertificate(self, certificate, folder):
        """"""
        url = self._url + "/sslcertificates/%s/export" % certificate
        params = {
            "f" : "json",
        }
        return self._get(url=url,
                         param_dict=params,
                        out_folder=folder)
132765
def acme_renew_certificates():
    '''
        
    '''

    for csr in glob(os.path.join(CERTIFICATES_PATH, '*.csr')):
        common_name = os.path.basename(csr)
        common_name = os.path.splitext(common_name)[0]

        certificate_path = "{}.crt".format(common_name)
        certificate_path = os.path.join(CERTIFICATES_PATH, certificate_path)

        with open(certificate_path) as file:
            crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                                    file.read())
            expiration = crt.get_notAfter()
            expiration = _parse_asn1_generalized_date(expiration)
            remaining = expiration - datetime.utcnow()
            if remaining > timedelta(days=30):
                print "No need to renew {} ({})".format(certificate_path, remaining)
                continue
            print "Renewing {} ({})".format(certificate_path, remaining)

        certificate_request_path = "{}.csr".format(common_name)
        certificate_request_path = os.path.join(CERTIFICATES_PATH,
                                                certificate_request_path)

        signed_cert = "{}-signed.crt".format(common_name)
        signed_cert = os.path.join(CERTIFICATES_PATH,
                                    signed_cert)

        _internal_sign_certificate(certificate_path, certificate_request_path,
                                    signed_cert)
487467
def create_dev_cert(name, dest):
    
    if not os.path.exists(dest):
        os.makedirs(dest)
    keygen.gen_ca_cert(name, dest, 3650)
255026
def generate_cert(name):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}
    cert = "{0}{1}.crt".format(get_certs_path(), name)
    key = "{0}{1}.key".format(get_certs_path(), name)

    # Checking if execution is needed.
    if os.path.isfile(cert) and os.path.isfile(key):
        ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key)
        return ret
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Certificate and key generation would be executed'
        return ret

    # Executing the command.
    cert_save = __salt__['icinga2.generate_cert'](name)
    if not cert_save['retcode']:
        ret['comment'] = "Certificate and key generated"
        ret['changes']['cert'] = "Executed. Certificate saved: {0}".format(cert)
        ret['changes']['key'] = "Executed. Key saved: {0}".format(key)
    return ret
511038
def get_default_ca_certs():
    
    # pylint: disable=protected-access
    if not hasattr(get_default_ca_certs, '_path'):
        for path in get_default_ca_cert_paths():
            if os.path.exists(path):
                get_default_ca_certs._path = path
                break
        else:
            get_default_ca_certs._path = None
    return get_default_ca_certs._path
1322666
static X509Certificate selfSignedCertificate() throws CertificateException {
        return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate(
                new ByteArrayInputStream(CERT.getBytes(CharsetUtil.US_ASCII))
        );
    }
267649
def _generate_url_root(protocol, host, port):
        
        return URL_ROOT_PATTERN.format(protocol=protocol, host=host, port=port)
400037
def set_cert(self, key_file=None, cert_file=None,
                 cert_reqs=None, ca_certs=None,
                 assert_hostname=None, assert_fingerprint=None,
                 ca_cert_dir=None):
        
        # If cert_reqs is not provided, we can try to guess. If the user gave
        # us a cert database, we assume they want to use it: otherwise, if
        # they gave us an SSL Context object we should use whatever is set for
        # it.
        if cert_reqs is None:
            if ca_certs or ca_cert_dir:
                cert_reqs = 'CERT_REQUIRED'
            elif self.ssl_context is not None:
                cert_reqs = self.ssl_context.verify_mode

        self.key_file = key_file
        self.cert_file = cert_file
        self.cert_reqs = cert_reqs
        self.assert_hostname = assert_hostname
        self.assert_fingerprint = assert_fingerprint
        self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
        self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
613800
def generate_adhoc_ssl_context():
    """"""
    from OpenSSL import SSL
    cert, pkey = generate_adhoc_ssl_pair()
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.use_privatekey(pkey)
    ctx.use_certificate(cert)
    return ctx
1242700
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType) throws IOException,
        GeneralSecurityException {
        return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, (X509ExtensionSet) null,
            null);
    }