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:it.govpay.core.utils.client.BasicClient.java

private BasicClient(String bundleKey, Connettore connettore) throws ClientException {

    if (connettore == null) {
        throw new ClientException("Connettore non configurato");
    }//from   ww w .ja v a 2 s  .  co m

    try {
        this.url = new URL(connettore.getUrl());
    } catch (Exception e) {
        throw new ClientException("La URL del connettore " + errMsg + " non e' valida: " + e);
    }
    sslContext = sslContexts.get(bundleKey);

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.SSL)) {
        isSslEnabled = true;
        if (sslContext == null) {
            try {
                FileInputStream finKeyStore = null;
                FileInputStream finTrustStore = null;

                KeyManager[] km = null;
                TrustManager[] tm = null;

                // Autenticazione CLIENT
                if (connettore.getTipoSsl().equals(EnumSslType.CLIENT)) {

                    if (connettore.getSslKsType() == null || connettore.getSslKsLocation() == null
                            || connettore.getSslKsPasswd() == null || connettore.getSslPKeyPasswd() == null)
                        throw new ClientException(
                                "Configurazione SSL Client del connettore " + errMsg + " incompleta.");

                    KeyStore keystore = KeyStore.getInstance(connettore.getSslKsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                    finKeyStore = new FileInputStream(connettore.getSslKsLocation());
                    keystore.load(finKeyStore, connettore.getSslKsPasswd().toCharArray());
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManagerFactory.init(keystore, connettore.getSslPKeyPasswd().toCharArray());
                    km = keyManagerFactory.getKeyManagers();
                }

                if (connettore.getSslTsType() == null || connettore.getSslTsLocation() == null
                        || connettore.getSslTsPasswd() == null || connettore.getSslType() == null)
                    throw new ClientException(
                            "Configurazione SSL Server del connettore " + errMsg + " incompleta.");

                // Autenticazione SERVER
                KeyStore truststore = KeyStore.getInstance(connettore.getSslTsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                finTrustStore = new FileInputStream(connettore.getSslTsLocation());
                truststore.load(finTrustStore, connettore.getSslTsPasswd().toCharArray());
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(truststore);
                tm = trustManagerFactory.getTrustManagers();

                // Creo contesto SSL
                sslContext = SSLContext.getInstance(connettore.getSslType());
                sslContext.init(km, tm, null);
                sslContexts.put(bundleKey, sslContext);
            } catch (Exception e) {
                throw new ClientException(e);
            }
        }
    }

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.HTTPBasic)) {
        ishttpBasicEnabled = true;
        httpBasicUser = connettore.getHttpUser();
        httpBasicPassword = connettore.getHttpPassw();
    }
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Builds an SSLConect that trusts the trust material in the KeyStore
 *
 * @param trustMaterial/*from  w  ww. j  a va 2  s  . c  o  m*/
 * @return
 */
public static SSLContext buildContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);

        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        ctx = SSLContext.getInstance("TLS");
        ctx.init(keyMgr.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public void sendRequest(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, KeyManagementException {

    //log.info("Sending to RapidSMS:\n" + msg);

    // Get the key store that includes self-signed cert as a "trusted"
    // entry.//from  ww  w  . jav a 2s.  co  m
    InputStream keyStoreStream = org.mule.util.IOUtils.getResourceAsStream("truststore.jks",
            GenerateORU_R01Alert.class);

    // Load the keyStore

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    //log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
    keyStoreStream.close();

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

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

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();

    callQueryFacility(msg);

}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore, String algorithm)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  w w  w.jav a 2  s.  c om*/
    log.debug("Initializing trust manager");
    if (StringUtils.isEmpty(algorithm)) {
        algorithm = TrustManagerFactory.getDefaultAlgorithm();
        log.debug("using default TrustManager algorithm [" + algorithm + "]");
    } else {
        log.debug("using configured TrustManager algorithm [" + algorithm + "]");
    }
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(algorithm);
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers;
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

private TrustManager[] createTrustManagers(final KeyStore trustStore)
        throws NoSuchAlgorithmException, KeyStoreException {
    if (trustStore == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but trust store is null");
        throw new IllegalArgumentException("TrustStore cannot be null");
    }//w w  w .j a  v a  2s. c om
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    return tmf.getTrustManagers();
}

From source file:org.apache.activemq.ActiveMQSslConnectionFactoryTest.java

public static TrustManager[] getTrustManager() throws Exception {
    TrustManager[] trustStoreManagers = null;
    KeyStore trustedCertStore = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE);

    trustedCertStore.load(new FileInputStream(ActiveMQSslConnectionFactoryTest.TRUST_KEYSTORE), null);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(trustedCertStore);/*w ww  .j a v  a 2s.com*/
    trustStoreManagers = tmf.getTrustManagers();
    return trustStoreManagers;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *///ww  w  .  j  a  v  a2 s.  c  o  m
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

From source file:com.micromux.cassandra.jdbc.CassandraConnection.java

private static SSLContext getSSLContext(String trustPath, String trustPass)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {

    FileInputStream tsf = null;//  w ww .  j  a v  a  2  s.  c  o  m
    SSLContext ctx = null;

    try {

        tsf = new FileInputStream(trustPath);
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, trustPass.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        ctx.init(null, tmf.getTrustManagers(), new SecureRandom());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (tsf != null) {
            try {
                tsf.close();
            } catch (IOException ix) {
                logger.warn("Error Closing Trust Store: " + trustPath, ix);
            }
        }

    }

    return ctx;

}

From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java

private void setSocketFactory(HttpsURLConnection connection) throws CommunicationException {
    try {/* w  w  w  . ja  v  a  2  s.c o  m*/
        if (sslFactory == null) {
            // initialize the SSL context
            String keyStoreLocation = getKeystoreLocation();
            if (keyStoreLocation == null) {
                throw new CommunicationException(
                        "Keystore not configured. A keystore must be placed in /config when using SSL.");
            }
            System.setProperty(KEY_STORE, keyStoreLocation);
            System.setProperty(TRUST_STORE, keyStoreLocation);
            KeyStore keyStore = KeyStore.getInstance("JKS");
            InputStream stream = new FileInputStream(keyStoreLocation);
            keyStore.load(stream, null);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tmf.getTrustManagers(), null);
            sslFactory = ctx.getSocketFactory();
        }
        connection.setSSLSocketFactory(sslFactory);
    } catch (NoSuchAlgorithmException | CertificateException | KeyManagementException | KeyStoreException
            | IOException e) {
        throw new CommunicationException(e);
    }
}