Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

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

Introduction

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

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

From source file:com.alliander.osgp.shared.usermanagement.AuthenticationClient.java

/**
 * Construct an AuthenticationClient instance.
 *
 * @param keystoreLocation/*from  w  ww . ja  va 2 s.  c  om*/
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the AuthenticationClient.
 *
 * @throws AuthenticationClientException
 *             In case the construction fails, an
 *             AuthenticationClientException will be thrown.
 */
public AuthenticationClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws AuthenticationClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers, true);
        if (this.webClient == null) {
            throw new AuthenticationClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());

        this.jacksonObjectMapper = new ObjectMapper();
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
    String provider_cert_string = preferences.getString(Provider.CA_CERT, "");

    java.security.cert.Certificate provider_certificate = ConfigHelper
            .parseX509CertificateFromString(provider_cert_string);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);/* w  ww. j  a  va 2  s . c om*/
    keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * http://www.coderanch.com/t/207318/sockets/java/do-hold-Java-default-SSL a
 * getter method for outputting the defauld certificate validator
 * //w w  w.  j a  v a 2s .  c om
 * @return
 */
private X509TrustManager getDefaultTrust() {
    TrustManagerFactory trustManagerFactory = null;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        trustManagerFactory.init((KeyStore) null);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("JVM Default Trust Managers:");
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        System.out.println(trustManager);

        if (trustManager instanceof X509TrustManager) {
            X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
            return x509TrustManager;
        }
    }
    return null;
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java

/**
 * Create a custom socket factory from trusted CA certificate.
 *
 * @return The factory./*from ww w  .  ja v  a  2  s  .com*/
 * @throws TlsException An error occured during initialization of the SSL context.
 * @since 0.8.0
 */
private SSLConnectionSocketFactory createSSLSocketFactory() throws TlsException {
    try {
        // Create Keystore with trusted certificate.
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trustedCert", trustedCaCert);

        // Initialize TrustManager.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // Create context usint this TrustManager.
        SSLContext context = SSLContext.getInstance(tlsVersion);
        context.init(null, tmf.getTrustManagers(), new SecureRandom());

        return new SSLConnectionSocketFactory(context, null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException e) {
        throw new TlsException(Error.INIT_SSL_CONTEXT, e);
    }
}

From source file:org.projectforge.core.ConfigXml.java

private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase)
        throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(is, passphrase.toCharArray());
    is.close();/*from   w  ww .  j ava  2s.  co  m*/
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { defaultTrustManager }, null);
    return context.getSocketFactory();
}

From source file:com.alliander.osgp.shared.usermanagement.OrganisationManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//from w w  w.j  a v a 2s .  co  m
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws OrganisationManagementClientException
 *             In case the construction fails, a
 *             OrganisationManagementClientException will be thrown.
 */
public OrganisationManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws OrganisationManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

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   ww w  . java 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:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory./*ww w.  jav a  2s  . co 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;
}