Example usage for javax.net.ssl TrustManagerFactory getDefaultAlgorithm

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

Introduction

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

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default TrustManagerFactory algorithm name.

Usage

From source file:com.longluo.volleydemo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/* ww  w .  j  a va2  s  .  c  o  m*/

        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

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

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

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

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//  ww w.  ja  va  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:org.apache.juddi.v3.client.cryptor.TransportSecurityHelper.java

public static boolean applyTransportSecurity(BindingProvider webServicePort) {
    try {/* w  w  w .ja v  a2  s. c  o m*/
        File currentdir = new File(".");
        String s = System.getProperty("javax.net.ssl.keyStore");
        String st = System.getProperty("javax.net.ssl.trustStore");
        log.info("Attempting to initialize keystore and truststore from " + s + " " + st);
        if (s == null) {
            log.warn("keystore isn't defined! " + s);
            return false;
        } else if (st == null) {
            log.warn("truststore isn't defined! " + s);
            return false;
        } else {
            File keystore = new File(s);
            if (keystore == null || !keystore.exists()) {
                log.warn("keystore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwd = System.getProperty("javax.net.ssl.keyStorePassword");
            if (pwd == null) {
                log.warn("keystore password isn't defined!");
                return false;
            }

            File truststore = new File(st);
            if (truststore == null || !truststore.exists()) {
                log.warn("truststore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwdt = System.getProperty("javax.net.ssl.trustStorePassword");
            if (pwdt == null) {
                log.warn("truststore password isn't defined!");
                return false;
            }

            if (keystore.exists()) {
                try {
                    log.info("Using keystore from " + keystore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());

                    log.info("Using truststore from " + truststore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());
                    //log.info("Using truststure from " + truststore.getAbsolutePath() + " current dir is " + currentdir.getAbsolutePath());
                    SSLContext sc = SSLContext.getInstance("SSLv3");

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

                    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(new FileInputStream(keystore), pwd.toCharArray());

                    kmf.init(ks, pwd.toCharArray());

                    String alg = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);

                    FileInputStream fis = new FileInputStream(st);
                    KeyStore kst = KeyStore.getInstance("jks");
                    kst.load(fis, pwdt.toCharArray());
                    fis.close();

                    tmFact.init(kst);

                    TrustManager[] tms = tmFact.getTrustManagers();

                    sc.init(kmf.getKeyManagers(), null, null);
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
                            sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
                    return true;
                } catch (Exception ex) {
                    log.warn("unable to establish ssl settings", ex);
                }
            }
        }
        return false;
    } catch (Exception x) {
        log.error("unexpected error", x);
    }
    return false;
}

From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java

static void setHoverflyTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException, URISyntaxException {
    // load your key store as a stream and initialize a KeyStore
    InputStream trustStream = findResourceOnClasspath("hoverfly.jks").toURL().openStream();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // load the stream to your store
    trustStore.load(trustStream, "hoverfly".toCharArray());

    // initialize a trust manager factory with the trusted store
    TrustManagerFactory trustFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init(trustStore);//from ww  w.  ja v  a 2  s.c o m

    // get the trust managers from the factory
    TrustManager[] trustManagers = trustFactory.getTrustManagers();

    // initialize an ssl context to use these managers and set as default
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagers, null);
    SSLContext.setDefault(sslContext);
}

From source file:com.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(Context context) throws IOException {
    try {//from   w w  w .  ja v  a  2 s .c o m
        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java

static HttpResponse sendSecureRequest(HttpRequest httpRequest, KeyStore keyStore)
        throws OIDCClientException, SSLConnectionException {
    Validate.notNull(httpRequest, "httpRequest");
    Validate.notNull(keyStore, "keyStore");

    TrustManagerFactory trustManagerFactory;
    SSLContext sslContext;/*from   w  w w . j  ava2s.c  om*/
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new SSLConnectionException("Failed to build SSL Context: " + e.getMessage(), e);
    }

    return sendSecureRequest(httpRequest, sslContext);
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static TrustManager[] createTrustManager(JSONObject sslConf) {
    TrustManager[] tms = null;/*from  w w w.j  a v a 2 s  . c  o m*/
    try {

        String TRUST_STORE = "etc/conf/trust.jks";
        String TRUST_STORE_PASSWORD = "Changeme_123";
        String TRUST_STORE_TYPE = "jks";
        if (sslConf != null) {
            TRUST_STORE = sslConf.getString("trustStore");
            TRUST_STORE_PASSWORD = sslConf.getString("trustStorePass");
            TRUST_STORE_TYPE = sslConf.getString("trustStoreType");
        }
        FileInputStream f_trustStore = new FileInputStream(TRUST_STORE);
        KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE);
        ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray());
        f_trustStore.close();

        String alg = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
        tmFact.init(ks);
        tms = tmFact.getTrustManagers();

    } catch (Exception e) {
        LOG.error("create TrustManager fail!", e);
    }
    return tms;
}

From source file:jp.pigumer.mqtt.Client.java

Optional<TrustManager[]> initTrustManagers() {
    return loadKeyStore().map(keyStore -> {
        try {/*from  w  w  w.  j  a va2s  . c o  m*/
            Security.addProvider(new BouncyCastleProvider());
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            return tmf.getTrustManagers();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * Creates trustmanagers from a truststore.
 *//*from   w w w  .  ja  v a2 s  .  co  m*/
public static TrustManager[] createTrustManagers(final KeyStore keystore, SecureConnectionDescription scd)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new LoggedX509TrustManager((X509TrustManager) trustmanagers[i], scd);
        }
    }
    return trustmanagers;
}

From source file:org.hyperic.util.security.DefaultSSLProviderImpl.java

private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore)
        throws KeyStoreException, IOException {
    try {/*from  w ww . jav  a 2s .  com*/
        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
        log.error("The algorithm is not supported: " + e, e);
        throw new KeyStoreException(e);
    }
}