Example usage for javax.net.ssl TrustManagerFactory init

List of usage examples for javax.net.ssl TrustManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory init.

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Loads the trusted certificate authorities according to the specified properties.
 *
 * @param properties properties//  www  .ja va2 s.  c  om
 * @return map of certificate authorities
 */
private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) {
    final Map<String, X509Certificate> certificateAuthorities = new HashMap<>();

    // get the path to the truststore
    final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    if (truststorePath == null) {
        throw new IllegalArgumentException("The truststore path is required.");
    }

    // get the truststore password
    final char[] truststorePassword;
    final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
    if (rawTruststorePassword == null) {
        truststorePassword = new char[0];
    } else {
        truststorePassword = rawTruststorePassword.toCharArray();
    }

    // load the configured truststore
    try (final FileInputStream fis = new FileInputStream(truststorePath)) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType());
        truststore.load(fis, truststorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        // consider any certificates in the truststore as a trusted ca
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
                    certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca);
                }
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException("Unable to load the configured truststore: " + e);
    }

    return certificateAuthorities;
}

From source file:org.pentaho.di.trans.steps.rest.Rest.java

private void setConfig() throws KettleException {

    if (data.config == null) {
        // Use ApacheHttpClient for supporting proxy authentication.
        data.config = new DefaultApacheHttpClientConfig();

        if (!Const.isEmpty(data.realProxyHost)) {
            // PROXY CONFIGURATION
            data.config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI,
                    "http://" + data.realProxyHost + ":" + data.realProxyPort);
            if (!Const.isEmpty(data.realHttpLogin) && !Const.isEmpty(data.realHttpPassword)) {
                data.config.getState().setProxyCredentials(AuthScope.ANY_REALM, data.realProxyHost,
                        data.realProxyPort, data.realHttpLogin, data.realHttpPassword);
            }/*w w  w .  j  av a2s. co  m*/
        } else {
            if (!Const.isEmpty(data.realHttpLogin)) {
                // Basic authentication
                data.basicAuthentication = new HTTPBasicAuthFilter(data.realHttpLogin, data.realHttpPassword);
            }
        }
        if (meta.isPreemptive()) {
            data.config.getProperties().put(ApacheHttpClientConfig.PROPERTY_PREEMPTIVE_AUTHENTICATION, true);
        }

        // SSL TRUST STORE CONFIGURATION
        if (!Const.isEmpty(data.trustStoreFile)) {

            try {
                KeyStore trustStore = KeyStore.getInstance("JKS");
                trustStore.load(new FileInputStream(data.trustStoreFile),
                        data.trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(trustStore);

                SSLContext ctx = SSLContext.getInstance("SSL");
                ctx.init(null, tmf.getTrustManagers(), null);

                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        if (isDebug()) {
                            logDebug("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
                        }
                        return true;
                    }
                };

                data.config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(hv, ctx));

            } catch (NoSuchAlgorithmException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.NoSuchAlgorithm"), e);
            } catch (KeyStoreException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyStoreException"), e);
            } catch (CertificateException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.CertificateException"), e);
            } catch (FileNotFoundException e) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Rest.Error.FileNotFound", data.trustStoreFile), e);
            } catch (IOException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.IOException"), e);
            } catch (KeyManagementException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyManagementException"), e);
            }
        }

    }
}

From source file:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory./*from  w ww. j a va  2  s .  c  o m*/
 * 
 * @param keyStoreBuilder
 *            the key store builder
 * @param trustStore
 *            the trust store
 * @param checkRevocation
 *            <code>true</code> if certificate revocations should be
 *            checked, else <code>false</code>
 * @throws WebServiceException
 *             if the creation failed
 */
public static SSLSocketFactory newSSLSocketFactory(KeyStore.Builder keyStoreBuilder, KeyStore trustStore,
        boolean checkRevocation) throws WebServiceException {
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    KeyStoreBuilderParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilder);
    try {
        keyManagerFactory.init(keyStoreBuilderParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    PKIXBuilderParameters pkixBuilderParameters;
    try {
        pkixBuilderParameters = new PKIXBuilderParameters(trustStore, null);
    } catch (KeyStoreException e) {
        String message = "The trust store is not initialized";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "The trust store does not contain any trusted certificate";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (NullPointerException e) {
        String message = "The trust store is null";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    pkixBuilderParameters.setRevocationEnabled(checkRevocation);
    CertPathTrustManagerParameters certPathTrustManagerParameters = new CertPathTrustManagerParameters(
            pkixBuilderParameters);
    try {
        trustManagerFactory.init(certPathTrustManagerParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    try {
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        String message = "Unable to initialize SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore)
        throws KeyStoreException, IOException {
    try {//  w  w  w . j  a v a 2 s.  c  o m
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(keystore);

        return trustManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        throw new KeyStoreException(e);
    }
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory.//from   ww w .  j  av  a  2s  . c  om
 * 
 * @return SSL Context
 * @throws ESCertificateException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws ESCertificateException {
    try {
        loadKeyStore();
        final KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        trustManagerFactory.init(keyStore);
        final SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return sslContext;
    } catch (final NoSuchAlgorithmException e) {
        throw new ESCertificateException(Messages.KeyStoreManager_29, e);
    } catch (final UnrecoverableKeyException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyStoreException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyManagementException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    }
}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }//from   w w w .  j a v  a 2 s  . co  m

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
    trustManagerFactory.init(truststore);

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureCaCert(WebClient webClient) {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);/*from w ww  .  j  ava 2 s.  c  o  m*/

        String alias = cert.getSubjectX500Principal().getName();
        trustStore.setCertificateEntry(alias, cert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        TrustManager[] existingTrustManagers = params.getTrustManagers();
        TrustManager[] trustManagers;

        if (existingTrustManagers == null || ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = trustManagerFactory.getTrustManagers();
        } else {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers,
                    trustManagerFactory.getTrustManagers());
        }

        params.setTrustManagers(trustManagers);

    } catch (Exception e) {
        log.error("Could not create trust manager for " + caCertFile, e);
    }
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load the TrustManagers from the supplied <code>
 * InputStream</code> using the supplied password.
 *
 * @param  is  <code>InputStream</code> containing the truststore
 * @param  password  <code>String</code> to unlock the truststore
 * @param  storeType  <code>String</code> of truststore
 *
 * @return  <code>TrustManager[]</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * TrustManagers/*  www.j ava  2 s  . c  o  m*/
 */
private TrustManager[] initTrustManager(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    TrustManager[] tm = null;
    if (is != null) {
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(this.loadKeyStore(is, password, storeType));
        tm = tmf.getTrustManagers();
    }
    return tm;
}

From source file:org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.java

/**
 * Override this method to take complete control over the SSL setup.
 * @throws Exception an Exception./*w w  w.j  a va2  s.  com*/
 * @since 1.4.4
 */
protected void setUpSSL() throws Exception {
    if (this.sslPropertiesLocation == null && this.keyStore == null && this.trustStore == null
            && this.keyStoreResource == null && this.trustStoreResource == null) {
        if (this.sslAlgorithmSet) {
            this.connectionFactory.useSslProtocol(this.sslAlgorithm);
        } else {
            this.connectionFactory.useSslProtocol();
        }
    } else {
        if (this.sslPropertiesLocation != null) {
            this.sslProperties.load(this.sslPropertiesLocation.getInputStream());
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String keyStoreName = getKeyStore();
        String trustStoreName = getTrustStore();
        String keyStorePassword = getKeyStorePassphrase();
        String trustStorePassword = getTrustStorePassphrase();
        String keyStoreType = getKeyStoreType();
        String trustStoreType = getTrustStoreType();
        char[] keyPassphrase = null;
        if (StringUtils.hasText(keyStorePassword)) {
            keyPassphrase = keyStorePassword.toCharArray();
        }
        char[] trustPassphrase = null;
        if (StringUtils.hasText(trustStorePassword)) {
            trustPassphrase = trustStorePassword.toCharArray();
        }
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        if (StringUtils.hasText(keyStoreName) || this.keyStoreResource != null) {
            Resource keyStoreResource = this.keyStoreResource != null ? this.keyStoreResource
                    : resolver.getResource(keyStoreName);
            KeyStore ks = KeyStore.getInstance(keyStoreType);
            ks.load(keyStoreResource.getInputStream(), keyPassphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyPassphrase);
            keyManagers = kmf.getKeyManagers();
        }
        if (StringUtils.hasText(trustStoreName) || this.trustStoreResource != null) {
            Resource trustStoreResource = this.trustStoreResource != null ? this.trustStoreResource
                    : resolver.getResource(trustStoreName);
            KeyStore tks = KeyStore.getInstance(trustStoreType);
            tks.load(trustStoreResource.getInputStream(), trustPassphrase);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing SSLContext with KM: " + Arrays.toString(keyManagers) + ", TM: "
                    + Arrays.toString(trustManagers) + ", random: " + this.secureRandom);
        }
        SSLContext context = createSSLContext();
        context.init(keyManagers, trustManagers, this.secureRandom);
        this.connectionFactory.useSslProtocol(context);
    }
}