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:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *///  ww w. jav a 2s. 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.quarterfull.newsAndroid.ssl.MemorizingTrustManager.java

X509TrustManager getTrustManager(KeyStore ks) {
    try {/*from  ww w .java2 s  .co  m*/
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);
        for (TrustManager t : tmf.getTrustManagers()) {
            if (t instanceof X509TrustManager) {
                return (X509TrustManager) t;
            }
        }
    } catch (Exception e) {
        // Here, we are covering up errors. It might be more useful
        // however to throw them out of the constructor so the
        // embedding app knows something went wrong.
        Log.e(TAG, "getTrustManager(" + ks + ")", 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  w  w.ja va  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  ww .j  ava 2s  .c om*/
        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);
    }
}

From source file:org.apache.directory.studio.connection.core.io.StudioTrustManager.java

private X509TrustManager getTrustManager(KeyStore trustStore) throws CertificateException {
    try {/*from   www .j a v  a  2s .  co  m*/
        Enumeration<String> aliases = trustStore.aliases();
        if (aliases.hasMoreElements()) {
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(trustStore);
            TrustManager[] permanentTrustManagers = factory.getTrustManagers();
            TrustManager permanentTrustManager = permanentTrustManagers[0];
            return (X509TrustManager) permanentTrustManager;
        }
    } catch (Exception e) {
        throw new CertificateException(Messages.StudioTrustManager_CantCreateTrustManager, e);
    }

    return null;
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SSLSocketFactory.java

private TrustManager[] loadTrustManagers() throws GeneralSecurityException, IOException {
    if (!StringUtils.hasText(trustStoreLocation)) {
        return null;
    }/*  ww w .  j  av a 2 s  . c o m*/

    char[] pass = (StringUtils.hasText(trustStorePass) ? trustStorePass.trim().toCharArray() : null);
    KeyStore keyStore = loadKeyStore(trustStoreLocation, pass);
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmFactory.init(keyStore);
    TrustManager[] tms = tmFactory.getTrustManagers();

    if (tms != null && trust != null) {
        // be defensive since the underlying impl might not give us a copy
        TrustManager[] clone = new TrustManager[tms.length];

        for (int i = 0; i < tms.length; i++) {
            TrustManager tm = tms[i];
            if (tm instanceof X509TrustManager) {
                tm = new TrustManagerDelegate((X509TrustManager) tm, trust);
            }
            clone[i] = tm;
        }
        tms = clone;
    }

    return tms;
}

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  ww.  j  a v  a2 s. co m*/
    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:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQInputEventAdapterListener.java

public RabbitMQInputEventAdapterListener(
        RabbitMQInputEventAdapterConnectionConfiguration rabbitMQInputEventAdapterConnectionConfiguration,
        InputEventAdapterConfiguration eventAdapterConfiguration,
        InputEventAdapterListener inputEventAdapterListener) {

    connectionFactory = new ConnectionFactory();
    this.rabbitMQInputEventAdapterConnectionConfiguration = rabbitMQInputEventAdapterConnectionConfiguration;
    this.queueName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_QUEUE_NAME);
    this.exchangeName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_EXCHANGE_NAME);
    this.exchangeType = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_EXCHANGE_TYPE);
    this.routeKey = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_QUEUE_ROUTING_KEY);
    this.consumerTagString = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.CONSUMER_TAG);
    this.adapterName = eventAdapterConfiguration.getName();
    this.eventAdapterListener = inputEventAdapterListener;
    this.tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    workerState = STATE_STOPPED;//from w  w w.  ja  v a 2s.c o m
    STATE_STARTED = 1;
    if (routeKey == null) {
        routeKey = queueName;
    }
    if (!eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED).equals("false")) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED));
            if (sslEnabled) {
                String keyStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_LOCATION);
                String keyStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_TYPE);
                String keyStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Truststore and keystore information is not provided");
                    }
                    if (StringUtils.isNotEmpty(sslVersion)) {
                        connectionFactory.useSslProtocol(sslVersion);
                    } else {
                        log.info("Proceeding with default SSL configuration");
                        connectionFactory.useSslProtocol();
                    }
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext context = SSLContext.getInstance(sslVersion);
                    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(context);
                }
            }
        } catch (IOException e) {
            handleException("TrustStore or KeyStore File path is incorrect. Specify KeyStore location or "
                    + "TrustStore location Correctly.", e);
        } catch (CertificateException e) {
            handleException("TrustStore or keyStore is not specified. So Security certificate"
                    + " Exception happened.  ", e);
        } catch (NoSuchAlgorithmException e) {
            handleException("Algorithm is not available in KeyManagerFactory class.", e);
        } catch (UnrecoverableKeyException e) {
            handleException("Unable to recover Key", e);
        } catch (KeyStoreException e) {
            handleException("Error in KeyStore or TrustStore Type", e);
        } catch (KeyManagementException e) {
            handleException("Error in Key Management", e);
        }
    }

    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT))) {
        try {
            int heartbeatValue = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT));
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    connectionFactory.setHost(rabbitMQInputEventAdapterConnectionConfiguration.getHostName());
    try {
        int port = Integer.parseInt(rabbitMQInputEventAdapterConnectionConfiguration.getPort());
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }
    connectionFactory.setUsername(rabbitMQInputEventAdapterConnectionConfiguration.getUsername());
    connectionFactory.setPassword(rabbitMQInputEventAdapterConnectionConfiguration.getPassword());
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST))) {
        connectionFactory.setVirtualHost(eventAdapterConfiguration.getProperties()
                .get(RabbitMQInputEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST));
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT))) {
        try {
            retryCountMax = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT));
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL))) {
        try {
            retryInterval = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL));
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry interval value. Proceeding with default value"
                    + " (30000ms)", e);
        }
    }
}

From source file:org.apache.hadoop.security.ssl.ReloadingX509TrustManager.java

X509TrustManager loadTrustManager() throws IOException, GeneralSecurityException {
    X509TrustManager trustManager = null;
    KeyStore ks = KeyStore.getInstance(type);
    String tstorePassword;//from  w w  w  .j  a  va  2s.c o  m
    if (passwordFileLocation != null) {
        tstorePassword = FileUtils.readFileToString(passwordFileLocation);
    } else {
        tstorePassword = password;
    }
    FileInputStream in = new FileInputStream(file);
    try {
        ks.load(in, tstorePassword.toCharArray());
        lastLoaded = file.lastModified();
        LOG.debug("Loaded truststore '" + file + "'");
    } finally {
        in.close();
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSLFactory.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:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;// w w w  .  j ava 2 s  .  c o  m
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

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

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}