This operation imports a certificate authority (CA)'s root and intermediate certificates into the keystore.
493201
def importRootCertificate(self, alias, rootCACertificate):
        """"""
        url = self._url + "/sslcertificates/importRootOrIntermediate"
        files = {}
        files['rootCACertificate'] = rootCACertificate
        params = {
            "f" : "json",
            "alias" : alias
        }
        return self._post(url=url,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            files=files,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
72185
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
    {
        try ( BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ) )
        {
            CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );

            int certCount = 0; // The file might contain multiple certs
            while ( inputStream.available() > 0 )
            {
                try
                {
                    Certificate cert = certFactory.generateCertificate( inputStream );
                    certCount++;
                    loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
                }
                catch ( CertificateException e )
                {
                    if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
                    {
                        // This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
                        // second cert, at which point we fail
                        return;
                    }
                    throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
                }
            }
        }
    }
257426
def certificate(self, value):
        """"""
        import os
        if os.path.isfile(value):
            self._certificatefile = value
699239
def import_keys(self, keyspec):
        
        for where, spec in keyspec.items():
            if where == 'file':
                for typ, files in spec.items():
                    if typ == 'rsa':
                        for fil in files:
                            _key = RSAKey(
                                key=import_private_rsa_key_from_file(fil),
                                use='sig')
                            _kb = KeyBundle()
                            _kb.append(_key)
                            self.keyjar.add_kb('', _kb)
            elif where == 'url':
                for iss, url in spec.items():
                    kb = KeyBundle(source=url)
                    self.keyjar.add_kb(iss, kb)
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
1069830
private SSLSocketFactory buildSslSocketFactory() {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", generateCertificate());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLSv1.2");
            context.init(null, tmf.getTrustManagers(), null);
            return context.getSocketFactory();

        } catch (Exception e) {
            throw new KubernetesClientException("Failure in generating SSLSocketFactory", e);
        }
    }
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
1166284
def import_jwks(self, jwks, issuer):
        
        try:
            _keys = jwks["keys"]
        except KeyError:
            raise ValueError('Not a proper JWKS')
        else:
            try:
                self.issuer_keys[issuer].append(
                    self.keybundle_cls(_keys, verify_ssl=self.verify_ssl))
            except KeyError:
                self.issuer_keys[issuer] = [self.keybundle_cls(
                    _keys, verify_ssl=self.verify_ssl)]
970082
function CA(root) {
  this.name = x509.getCAName(root);
  this.trusted = x509.isTrusted(root);
  this.cert = root;
}
989454
def init(self, ca, csr, **kwargs):
        

        c = self.model(ca=ca)
        c.x509, csr = self.sign_cert(ca, csr, **kwargs)
        c.csr = csr.public_bytes(Encoding.PEM).decode('utf-8')
        c.save()

        post_issue_cert.send(sender=self.model, cert=c)
        return c
460053
public void addCACertificatesToTrustStore(BufferedInputStream bis) throws CryptoException, InvalidArgumentException {

        if (bis == null) {
            throw new InvalidArgumentException("The certificate stream bis cannot be null");
        }

        try {
            final Collection<? extends Certificate> certificates = cf.generateCertificates(bis);
            for (Certificate certificate : certificates) {
                addCACertificateToTrustStore(certificate);
            }

        } catch (CertificateException e) {
            throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e);
        }
    }
1101672
def createClientCertificate(self, name, noPass = True, keyLength = 2048, days = 375):
        
        if not name:
            raise ValueError('Require name')
        configPath, keyPath, csrPath, certPath = \
                os.path.join(self.basePath, self.FILE_CONFIG), \
                os.path.join(self.basePath, self.DIR_PRIVATE, '%s.key.pem' % name), \
                os.path.join(self.basePath, self.DIR_CSR, '%s.csr.pem' % name), \
                os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name)
        if os.path.isfile(keyPath):
            raise ValueError('Key file exists at [%s]' % keyPath)
        if os.path.isfile(csrPath):
            raise ValueError('CSR file exists at [%s]' % csrPath)
        if os.path.isfile(certPath):
            raise ValueError('Certificate file exists at [%s]' % certPath)
        # Generate the key
        if subprocess.call([ 'openssl', 'genrsa', '-aes256', '-out', keyPath, str(keyLength) ] if not noPass else [ 'openssl', 'genrsa', '-out', keyPath, str(keyLength) ]) != 0:
            raise ValueError('Failed to create key')
        # Generate the csr
        if subprocess.call([ 'openssl', 'req', '-config', configPath, '-key', keyPath, '-new', '-sha256', '-out', csrPath ]) != 0:
            raise ValueError('Failed to create CSR')
        # Generate the certificate
        if subprocess.call([ 'openssl', 'ca', '-config', configPath, '-extensions', 'usr_cert', '-days', str(days), '-notext', '-md', 'sha256', '-in', csrPath, '-out', certPath ]) != 0:
            raise ValueError('Failed to create certificate')
891837
public void installCertificates(final String key, final String cert, final String chain)
	{
		try
		{
			final File keyFile = File.createTempFile("key", ".pem");
			final File certFile = File.createTempFile("cert", ".pem");
			final File chainFile = File.createTempFile("chain", ".pem");

			try
			{
				FileHelper.write(keyFile, key);
				FileHelper.write(certFile, cert);
				FileHelper.write(chainFile, chain);

				final Execed process = Exec.rootUtility(new File(binPath, "cert-update").getAbsolutePath(),
				                                        keyFile.getAbsolutePath(),
				                                        certFile.getAbsolutePath(),
				                                        chainFile.getAbsolutePath());

				process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0);
			}
			finally
			{
				FileUtils.deleteQuietly(keyFile);
				FileUtils.deleteQuietly(certFile);
				FileUtils.deleteQuietly(chainFile);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("Error executing cert-update command", e);
		}
	}
821483
public static void updateWithCaPem(KeyStore pTrustStore, File pCaCert)
            throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
        InputStream is = new FileInputStream(pCaCert);
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);

            String alias = cert.getSubjectX500Principal().getName();
            pTrustStore.setCertificateEntry(alias, cert);
        } finally {
            is.close();
        }
    }
332636
def _load_ca_certs(cls, session: AppSession, clean: bool=True):
        '''
        '''
        args = session.args

        if session.ca_certs_filename:
            return session.ca_certs_filename

        certs = set()

        if args.use_internal_ca_certs:
            pem_filename = os.path.join(
                os.path.dirname(__file__), '..', '..', 'cert', 'ca-bundle.pem'
            )
            certs.update(cls._read_pem_file(pem_filename, from_package=True))

        if args.ca_directory:
            if os.path.isdir(args.ca_directory):
                for filename in os.listdir(args.ca_directory):
                    if os.path.isfile(filename):
                        certs.update(cls._read_pem_file(filename))
            else:
                _logger.warning(__(
                    _('Certificate directory {path} does not exist.'),
                    path=args.ca_directory
                ))

        if args.ca_certificate:
            if os.path.isfile(args.ca_certificate):
                certs.update(cls._read_pem_file(args.ca_certificate))
            else:
                _logger.warning(__(
                    _('Certificate file {path} does not exist.'),
                    path=args.ca_certificate
                ))

        session.ca_certs_filename = certs_filename = tempfile.mkstemp(
            suffix='.pem', prefix='tmp-wpull-')[1]

        def clean_certs_file():
            os.remove(certs_filename)

        if clean:
            atexit.register(clean_certs_file)

        with open(certs_filename, 'w+b') as certs_file:
            for cert in certs:
                certs_file.write(cert)

        _logger.debug('CA certs loaded.')
870990
private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file,
            final char[] tsp, final TrustStrategy trustStrategy)
                    throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
        Args.notNull(file, "Truststore file"); //$NON-NLS-1$
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final FileInputStream instream = new FileInputStream(file);
        try {
            trustStore.load(instream, tsp);
        } finally {
            instream.close();
        }
        return builder.loadTrustMaterial(trustStore, trustStrategy);
    }
907359
def open(store_name)
      certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name))
      unless certstore_handler
        last_error = FFI::LastError.error
        raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error)
      end
      add_finalizer(certstore_handler)
      certstore_handler
    end