Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java

private TrustManager[] doSSLVerification() throws Exception {
    TrustManager[] trustManagers = null;
    if (this.getEnableSSLVerification()) {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(this.getKeyStore());
        trustManagers = tmf.getTrustManagers();
    } else {/*from  w  w w. j  a  v a 2 s  .  c o m*/
        // Create a trust manager that does not validate certificate chains
        trustManagers = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
    }
    return trustManagers;
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * This sets the trust managers that will be used for all TLS and SSL connections to the ldap. This method will
 * remove any cached results and initialize the connection manager.
 * //from  w w  w. j ava 2 s  .c o m
 * @see #clearCache()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param tc <code>X509Credential</code> to create TrustManagers with
 */
public void setSslTrustManagers(X509Credential tc) {
    if (tc != null) {
        try {
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            for (X509Certificate c : tc.getEntityCertificateChain()) {
                keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c);
            }
            tmf.init(keystore);
            sslTrustManagers = tmf.getTrustManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing trust managers", e);
        } catch (IOException e) {
            log.error("Error initializing trust managers", e);
        }
    }
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;/*ww  w.  j  av  a  2s  . com*/
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

From source file:iracing.webapi.IracingWebApi.java

private void installCerts() throws Exception {
    String host = "members.iracing.com";
    int port = 443;

    char[] password = CERT_STORE_PASSWORD.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char seperator = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }/*from  w ww.j a  v  a 2s .  c om*/
    }
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(in, password);
    } catch (Exception e) {
    }
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    SSLSocket socket = null;
    try {
        socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        socket.startHandshake();
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (socket != null)
            socket.close();
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null)
        return;

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
    }

    for (int count = 0; count < chain.length; count++) {
        X509Certificate cert = chain[count];
        String alias = host + "-" + (count + 1);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream("jssecacerts");
        try {
            ks.store(out, password);
        } finally {
            out.close();
        }
    }
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);/* ww w  .  j  a v a 2 s  .com*/
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}

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   w w  w .  j  a  va 2  s .  c  o  m

    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);
    }

}

From source file:org.apache.hive.jdbc.HiveConnection.java

SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLConnectionSocketFactory socketFactory = null;

    try {//  w  w  w .  j  a v  a2 s  .  co m
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE);
        String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(
                    JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLConnectionSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

private TrustManager[] getTrustManagers()
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    final InputStream truststoreis;
    TrustManager[] trustManager;/* w  ww  . j a  v  a 2s .com*/
    if (StringUtils.isBlank(this.truststore) || StringUtils.isBlank(this.truststorePasswd)) {
        //This means we dont want certificate authentication of any type, however we want only encryption during https call
        trustManager = new TrustManager[] { new NoOpTrustManager() };
    } else {
        // Load the Client Truststore
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        final KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());

        //see if the file is present otherwise read from class path
        File trustStoreFile = new File(this.truststore);
        if (trustStoreFile.exists()) {
            truststoreis = new FileInputStream(trustStoreFile);
        } else {
            LogHandler.warn("File not found, so trying to read it from class path now");
            truststoreis = HttpClient.class.getResourceAsStream(this.truststore);
        }
        truststore.load(truststoreis, this.truststorePasswd.toCharArray());
        tmf.init(truststore);
        trustManager = tmf.getTrustManagers();
        truststoreis.close();
    }
    return trustManager;
}