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:com.cloudera.nav.sdk.client.SSLUtils.java

private static X509TrustManager loadTrustManager(String type, String file, String password)
        throws IOException, GeneralSecurityException {
    X509TrustManager trustManager = null;
    KeyStore ks = KeyStore.getInstance(type);
    try (FileInputStream in = new FileInputStream(file)) {
        ks.load(in, password.toCharArray());
        LOG.debug("Loaded truststore '" + file + "'");
    }//  w  ww  .  j  av  a  2s  .co  m

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSLCERTIFICATE);
    trustManagerFactory.init(ks);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    for (TrustManager trustManager1 : trustManagers) {
        if (trustManager1 instanceof X509TrustManager) {
            trustManager = (X509TrustManager) trustManager1;
            break;
        }
    }
    return trustManager;
}

From source file:ddf.security.common.util.CommonSSLFactory.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communication./*from w w  w . ja v a 2s  .co m*/
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws IOException
 */
public static SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws IOException {
    String methodName = "createSocket";
    logger.debug("ENTERING: " + methodName);

    try {
        logger.debug("trustStoreLoc = " + trustStoreLoc);
        FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
        logger.debug("keyStoreLoc = " + keyStoreLoc);
        FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

        // truststore stuff
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading trustStore");
            trustStore.load(trustFIS, trustStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        logger.debug("trust manager factory initialized");

        // keystore stuff
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading keyStore");
            keyStore.load(keyFIS, keyStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(keyFIS);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePass.toCharArray());
        logger.debug("key manager factory initialized");

        // ssl context
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        sslCtx.getDefaultSSLParameters().setNeedClientAuth(true);
        sslCtx.getDefaultSSLParameters().setWantClientAuth(true);
        logger.debug(exiting + methodName);

        return sslCtx.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to initialize the SSL context.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.debug(exiting + methodName);
        throw new IOException(
                "Problems creating SSL socket. Usually this is "
                        + "referring to the certificate sent by the server not being trusted by the client.",
                e);
    } catch (UnrecoverableKeyException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to load keystore. " + keyStoreLoc, e);
    } catch (KeyStoreException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to read keystore. " + keyStoreLoc, e);
    }
}

From source file:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName/*from   ww  w  . java  2 s.  co  m*/
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}

From source file:com.mani.fileupload.http.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//  w w w  .  j a va 2s  .  c om

        // Client should send the valid key to Server 
        InputStream clientStream = null;
        char[] password = null;

        clientStream = FileUploadApplication.getContext().getResources().openRawResource(R.raw.client);
        password = "fileupload".toCharArray();

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

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

        // CA key obtained from server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = FileUploadApplication.getContext().getResources().openRawResource(R.raw.ca);

        try {
            trustStore.load(instream, "casecret".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
        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:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }/*  w ww  .  j  av  a2s.co  m*/
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:ninja.standalone.StandaloneHelper.java

static public SSLContext createSSLContext(URI keystoreUri, char[] keystorePassword, URI truststoreUri,
        char[] truststorePassword) throws Exception {

    // load keystore
    KeyStore keystore = loadKeyStore(keystoreUri, keystorePassword);
    KeyManager[] keyManagers;/*from  w  ww. j a  va 2s. co m*/
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keystorePassword);
    keyManagers = keyManagerFactory.getKeyManagers();

    // load truststore
    KeyStore truststore = loadKeyStore(truststoreUri, truststorePassword);
    TrustManager[] trustManagers;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(truststore);
    trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);

    return sslContext;
}

From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.OAuthRequestInterceptor.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)/*  w  w w  . j  a v  a  2  s . com*/
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    SSLContext sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext.getSocketFactory();
}

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);
    }//  w w w  .  j  a va  2s  . 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:org.apache.ranger.services.nifi.client.NiFiConnectionMgr.java

private static SSLContext createSslContext(final String keystore, final char[] keystorePasswd,
        final String keystoreType, final String truststore, final char[] truststorePasswd,
        final String truststoreType, final String protocol) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }/*from   ww  w .j  av a2 s .  co  m*/
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:com.codedx.burp.security.SSLConnectionSocketFactoryFactory.java

private static X509TrustManager getDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory defaultFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    defaultFactory.init((KeyStore) null);

    TrustManager[] managers = defaultFactory.getTrustManagers();
    for (TrustManager mgr : managers) {
        if (mgr instanceof X509TrustManager) {
            return (X509TrustManager) mgr;
        }//ww  w.j  a va2s .co m
    }

    return null;
}