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: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  . ja  v a 2 s.  c  om*/
    trustStoreManagers = tmf.getTrustManagers();
    return trustStoreManagers;
}

From source file:org.comixwall.pffw.Utils.java

/**
 * Create an SSL context which trusts the PFFW server certificate.
 * PFFW server certificate is self signed, hence is not verified by the default SSL context.
 *
 * @param owner Fragment which initiated the call to this method.
 * @return SSL context.//from w ww . j  ava 2s. c  om
 */
static SSLContext getSslContext(final Fragment owner) {
    SSLContext sslContext = null;
    try {
        // Load our crt from an InputStream
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream crtInput = owner.getResources().openRawResource(
                owner.getResources().getIdentifier("server", "raw", owner.getActivity().getPackageName()));

        Certificate crt;
        try {
            crt = cf.generateCertificate(crtInput);
            logger.finest("server.crt=" + ((X509Certificate) crt).getSubjectDN());
        } finally {
            crtInput.close();
        }

        // Create a KeyStore containing our trusted crt
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("server.crt", crt);

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

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

    } catch (Exception e) {
        e.printStackTrace();
        logger.severe("getSslContext exception: " + e.toString());
    }
    return sslContext;
}

From source file:org.jasig.cas.authentication.FileTrustStoreSslSocketFactory.java

/**
 * Gets trust manager./*  w  w  w . j  a v a2s .c om*/
 *
 * @param algorithm the algorithm
 * @param keystore the keystore
 * @return the trust manager
 * @throws Exception the exception
 */
private static X509TrustManager getTrustManager(final String algorithm, final KeyStore keystore)
        throws Exception {
    final TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
    factory.init(keystore);
    return (X509TrustManager) factory.getTrustManagers()[0];
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLTrustManagerFactory.java

public static TrustManager[] getTrustManagers(KeyStore truststore, String trustpass) {
    TrustManager[] trustManagers;
    try {/*from   w  ww  .j  a v a 2  s.  c  o m*/
        if (truststore == null) {
            trustManagers = null;
        } else {
            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            if (trustpass == null) {
                trustpass = SSLConfig.getc2sTrustPassword();
            }

            trustFactory.init(truststore);

            trustManagers = trustFactory.getTrustManagers();
        }
    } catch (KeyStoreException e) {
        trustManagers = null;
        log.error("SSLTrustManagerFactory startup problem.", e);
    } catch (NoSuchAlgorithmException e) {
        trustManagers = null;
        log.error("SSLTrustManagerFactory startup problem.", e);
    }
    return trustManagers;
}

From source file:io.fabric8.utils.cxf.WebClients.java

public static void configureCaCert(WebClient webClient, String caCertData, File caCertFile) {
    try {//  ww w.  j a  v a2  s. com
        KeyStore trustStore = createTrustStore(caCertData, caCertFile);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

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

        TLSClientParameters params = conduit.getTlsClientParameters();

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

        TrustManager[] existingTrustManagers = params.getTrustManagers();

        if (!ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers, trustManagers);
        }

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

From source file:com.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }/*from w ww .ja va2 s  .  c  o m*/

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}

From source file:gobblin.security.ssl.SSLContextFactory.java

/**
 * Create a {@link SSLContext} instance//w  ww.j  a  v a  2s  .  c o  m
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType,
        File trustStoreFile, String trustStorePassword) {
    if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME)
            && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
        throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
    }

    try {
        // Load KeyStore
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

        // Load TrustStore
        KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
        trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

        // Set KeyManger from keyStore
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
        kmf.init(keyStore, keyStorePassword.toCharArray());

        // Set TrustManager from trustStore
        TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
        trustFact.init(trustStore);

        // Set Context to TLS and initialize it
        SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  ww w  .j  a  v  a2 s.c  o  m*/
    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 AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from w  ww. j ava  2 s  .com
    System.out.println("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 AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from w ww .  j  a  v  a2s.c o  m
    LOG.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();

    LOG.debug("Found " + trustmanagers.length + " trust managers");

    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        } else {
            System.out.println("non 509 trust manager: class is " + trustmanagers[i].getClass().getName());
        }
    }
    return trustmanagers;
}