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:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Loads certs from//from  ww  w . ja  v a2s .co  m
 *  the ~/.i2p/certificates/ and $I2P/certificates/ directories.
 */
private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts,
        String relativeCertPath) throws GeneralSecurityException {
    Log log = context.logManager().getLog(I2PSSLSocketFactory.class);
    KeyStore ks;
    if (loadSystemCerts) {
        ks = KeyStoreUtil.loadSystemKeyStore();
        if (ks == null)
            throw new GeneralSecurityException("Key Store init error");
    } else {
        try {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, "".toCharArray());
        } catch (IOException ioe) {
            throw new GeneralSecurityException("Key Store init error", ioe);
        }
    }

    File dir = new File(context.getConfigDir(), relativeCertPath);
    int adds = KeyStoreUtil.addCerts(dir, ks);
    int totalAdds = adds;
    if (adds > 0) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
    }

    File dir2 = new File(context.getBaseDir(), relativeCertPath);
    if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) {
        adds = KeyStoreUtil.addCerts(dir2, ks);
        totalAdds += adds;
        if (adds > 0) {
            if (log.shouldLog(Log.INFO))
                log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
        }
    }
    if (totalAdds > 0 || loadSystemCerts) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded total of " + totalAdds + " new trusted certificates");
    } else {
        String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath()
                + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? ""
                        : (" and " + dir2.getAbsolutePath()))
                + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath
                + " from the router to the directory.";
        // don't continue, since we didn't load the system keystore, we have nothing.
        throw new GeneralSecurityException(msg);
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    sslc.init(null, tmf.getTrustManagers(), context.random());
    return sslc.getSocketFactory();
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory//from ww w .  ja  v a 2  s  .c  om
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build SSL Socket factory./*  w w  w.  ja  v  a  2s.  com*/
 * @param config Http client configuration
 * @return SSL socket factory.
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static SSLContext buildSSLContext(HttpClientConfig config) throws IOException, GeneralSecurityException {

    KeyManagerFactory kmf = null;
    if (isSslKeyManagerEnabled(config)) {
        kmf = getKeyManagerFactory(config.getKeyStorePath(), new StoreProperties(config.getKeyStorePassword(),
                config.getKeyManagerType(), config.getKeyStoreType()));
    }
    TrustManagerFactory tmf = null;
    if (isSslTrustStoreEnbaled(config)) {
        StoreProperties storeProperties = new StoreProperties(config.getTrustStorePassword(),
                config.getTrustManagerType(), config.getTrustStoreType());
        tmf = getTrustManagerFactory(config.getTrustStorePath(), storeProperties);
    }

    SSLContext sslContext = SSLContext.getInstance(config.getSslContextType());
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
            null);

    return sslContext;
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java

/**
 * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}.
 *
 * @return the trust manager//from  ww w .  j av  a2  s . c om
 */
protected static X509TrustManager getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}

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

/**
 * Same as buildContext(), but wraps all X509TrustManagers in a SavableTrustManager to provide
 * UntrustedCertificateExceptions so that when a client connects to a server it does not trust,
 * the program can recover the key and ask the user if they wish to trust it.
 *
 * @param trustMaterial//from  w  w w.jav a 2 s .c o  m
 * @return
 */
public static SSLContext buildClientContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);
        ctx = SSLContext.getInstance("TLS");
        //key manager factory go!
        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        TrustManager[] trustManagers = tmf.getTrustManagers();

        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                System.out.println("Wrapped a trust manager.");
                trustManagers[i] = new SavableTrustManager((X509TrustManager) trustManagers[i]);
            }
        }

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

    return ctx;
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);/*from  w  ww. ja v  a2 s .co m*/
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception {

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

    keyStore.load(null, null);/*from  w  w w  .j av  a 2  s .c  om*/

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }

        try {
            PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey());

            if (privateKey == null) {
                _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId());

                continue;
            }

            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            if (x509Certificate == null) {
                _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId());

                continue;
            }

            keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate);

            keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(),
                    new Certificate[] { x509Certificate });
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }
    }

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

    keyManagerFactory.init(keyStore, "".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(keyStore);

    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:com.t2auth.AuthUtils.java

public static SSLContext getSslContext(Context ctx) {
    InputStream in = null;//  w  w  w . j  av a  2  s  .c  om

    if (sSslContext == null) {
        try {
            sSslContext = SSLContext.getInstance("TLS");
            try {
                if (sKey == null) {
                    sKey = KeyStore.getInstance("BKS");
                    in = ctx.getResources().openRawResource(R.raw.keystore);
                    sKey.load(in, "itsatrap".toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(sKey);
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
                kmf.init(sKey, "itsatrap".toCharArray());

                sSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                return sSslContext;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    } else {
        return sSslContext;
    }

    return null;
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory//from w  w  w.j  ava 2s  .  co m
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

private static SocketFactory extractSocketFactory(String trustStore, String trustStorePassword, String keyStore,
        String keyStorePassword) {
    TrustManager[] trustManagers;
    KeyManager[] keyManagers;//from ww w  .j a  va  2 s  .c om

    try (InputStream trustStream = new FileInputStream(trustStore)) {
        char[] trustStorePass = trustStorePassword.toCharArray();
        KeyStore trustStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStoreJKS.load(trustStream, trustStorePass);
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStoreJKS);
        trustManagers = trustFactory.getTrustManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Trust store file not found for secure connections to mongodb. "
                + "Trust Store file path : '" + trustStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Trust Store file path : '" + trustStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Trust Store file path : '" + trustStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Trust Store file path : '" + trustStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException("Exception in creating trust store, no Provider supports aKeyStoreSpi "
                + "implementation for the specified type. Trust Store file path : '" + trustStore + "'.", e);
    }

    try (InputStream keyStream = new FileInputStream(keyStore)) {
        char[] keyStorePass = keyStorePassword.toCharArray();
        KeyStore keyStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStoreJKS.load(keyStream, keyStorePass);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStoreJKS, keyStorePass);
        keyManagers = keyManagerFactory.getKeyManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Key store file not found for secure connections to mongodb. "
                + "Key Store file path : '" + keyStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Key Store file path : '" + keyStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Key Store file path : '" + keyStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException(
                "Exception in creating trust store, no Provider supports aKeyStoreSpi "
                        + "implementation for the specified type. Key Store file path : '" + keyStore + "'.",
                e);
    } catch (UnrecoverableKeyException e) {
        throw new MongoTableException(
                "Key in the keystore cannot be recovered. " + "Key Store file path : '" + keyStore + "'.", e);
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);
        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        throw new MongoTableException(
                "Error in validating the key in the key store/ trust store. " + "Trust Store file path : '"
                        + trustStore + "'. " + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException(
                " SSL Algorithm used to create SSL Socket Factory for mongodb connections " + "is not found.",
                e);
    }

}