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:org.apache.ranger.plugin.util.RangerRESTClient.java

private TrustManager[] getTrustManagers() {
    TrustManager[] tmList = null;

    String trustStoreFilepwd = getCredential(mTrustStoreURL, mTrustStoreAlias);

    if (!StringUtil.isEmpty(mTrustStoreFile) && !StringUtil.isEmpty(trustStoreFilepwd)) {
        InputStream in = null;//from  w w w.j ava2s  .co m

        try {
            in = getFileInputStream(mTrustStoreFile);

            if (in != null) {
                KeyStore trustStore = KeyStore.getInstance(mTrustStoreType);

                trustStore.load(in, trustStoreFilepwd.toCharArray());

                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(RANGER_SSL_TRUSTMANAGER_ALGO_TYPE);

                trustManagerFactory.init(trustStore);

                tmList = trustManagerFactory.getTrustManagers();
            } else {
                LOG.error("Unable to obtain keystore from file [" + mTrustStoreFile + "]");
            }
        } catch (KeyStoreException e) {
            LOG.error("Unable to obtain from KeyStore", e);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("SSL algorithm is available in the environment", e);
        } catch (CertificateException e) {
            LOG.error("Unable to obtain the requested certification ", e);
        } catch (FileNotFoundException e) {
            LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
        } catch (IOException e) {
            LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
        } finally {
            close(in, mTrustStoreFile);
        }
    }

    return tmList;
}

From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java

public void initMemoryTrustManager(boolean forcereload)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    if (memoryTrustManager != null && !forcereload) {
        return;/*ww  w  .  jav a2 s. c  o  m*/
    }
    try {
        if (memoryKeyStore == null) {
            memoryKeyStore = KeyStore.getInstance("JKS");
        }

        try {
            memoryKeyStore.load(null, persistedKeystorePassword);
        } catch (IOException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
        } catch (CertificateException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(memoryKeyStore);

        TrustManager tms[] = tmf.getTrustManagers();

        // Iterate over the returned trustmanagers, look for an instance of X509TrustManager.
        // If found, use that as our "default" trust manager.
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                memoryTrustManager = (X509TrustManager) tms[i];
                break;
            }
        }
        LOG.log(Level.FINER, "MemoryTrustManager=" + memoryTrustManager);
    } catch (KeyStoreException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;

    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;

    } catch (RuntimeException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {

    final KeyManager km[];
    final TrustManager tm[];

    // Put the key and certs in the user keystore (if available)
    if (this.ks != null) {
        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(this.ks, this.passphrase.toCharArray());
        km = kmf.getKeyManagers();//from w w w.j av a2s.  c om
    } else {
        km = null;
    }
    // Now make a truststore to verify the server
    if (this.certChain != null && this.certChain.length > 0) {
        final KeyStore trustks = KeyStore.getInstance("jks");
        trustks.load(null, "foo123".toCharArray());
        // add trusted CA cert
        trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustks);
        tm = tmf.getTrustManagers();
    } else {
        tm = null;
    }
    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.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory/*from  w  w w.  j a  va2s.  c  o  m*/
 */
public void initConnectionFactory() {
    connectionFactory = new ConnectionFactory();
    String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
    String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
    String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
    String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
    String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
    String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
    String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
    String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
    String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
    String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);

    if (!StringUtils.isEmpty(heartbeat)) {
        try {
            int heartbeatValue = Integer.parseInt(heartbeat);
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionTimeout)) {
        try {
            int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
            connectionFactory.setConnectionTimeout(connectionTimeoutValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }

    if (!StringUtils.isEmpty(sslEnabledS)) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
            if (sslEnabled) {
                String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
                String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
                String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.warn(
                            "Truststore and keystore information is not provided correctly. 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 c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (Exception e) {
            log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
        }
    }

    if (!StringUtils.isEmpty(retryCountS)) {
        try {
            retryCount = Integer.parseInt(retryCountS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }

    if (!StringUtils.isEmpty(hostName)) {
        connectionFactory.setHost(hostName);
    } else {
        handleException("Host name is not defined");
    }

    try {
        int port = Integer.parseInt(portValue);
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }

    if (!StringUtils.isEmpty(userName)) {
        connectionFactory.setUsername(userName);
    }

    if (!StringUtils.isEmpty(password)) {
        connectionFactory.setPassword(password);
    }

    if (!StringUtils.isEmpty(virtualHost)) {
        connectionFactory.setVirtualHost(virtualHost);
    }

    if (!StringUtils.isEmpty(retryIntervalS)) {
        try {
            retryInterval = Integer.parseInt(retryIntervalS);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading retry interval value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    if (!StringUtils.isEmpty(serverRetryIntervalS)) {
        try {
            int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
            connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading server retry interval value. Proceeding with default value",
                    e);
        }
    }

    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(false);
}

From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java

public void initPersistedTrustManager(boolean forcereload)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    if (persistedTrustManager != null && !forcereload) {
        return;//from  ww  w . j ava  2 s. c  o m
    }

    String homedir = System.getProperty("user.home");
    String fileNameTemplate = ConfigurationHelper.USER_CONFIG_DIRECTORY
            + ConfigurationHelper.getStringProperty("ssl.keystore.filename", "cacerts");
    String fileName = MessageFormat.format(fileNameTemplate, homedir);
    persistedKeystoreFile = new File(fileName);

    try {
        persistedKeyStore = KeyStore.getInstance("JKS");
        try {
            FileInputStream fis = null;
            if (persistedKeystoreFile.exists()) {
                fis = new FileInputStream(persistedKeystoreFile);
            }
            persistedKeyStore.load(fis, persistedKeystorePassword);
        } catch (FileNotFoundException e) {
            // Don't Care. Go on.
            LOG.log(Level.WARNING, "Unexpected Exception", e);
        } catch (IOException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
        } catch (CertificateException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(persistedKeyStore);

        TrustManager tms[] = tmf.getTrustManagers();

        // Iterate over the returned trustmanagers, look for an instance of X509TrustManager.
        // If found, use that as our "default" trust manager.
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                persistedTrustManager = (X509TrustManager) tms[i];
                break;
            }
        }
        LOG.log(Level.FINER, "persistedTrustManager=" + persistedTrustManager);
    } catch (KeyStoreException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;

    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;
    } catch (RuntimeException e) {
        LOG.log(Level.WARNING, "Unexpected Exception", e);
        throw e;
    }
}

From source file:org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl.java

/**
 * Initializes the SSL Context/*from w w  w.j  a v a  2 s . com*/
 */
private void initSSLConnection()
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

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

From source file:it.govpay.core.utils.client.BasicClient.java

private BasicClient(String bundleKey, Connettore connettore) throws ClientException {

    if (connettore == null) {
        throw new ClientException("Connettore non configurato");
    }//from w w  w.jav a 2 s  . c o m

    try {
        this.url = new URL(connettore.getUrl());
    } catch (Exception e) {
        throw new ClientException("La URL del connettore " + errMsg + " non e' valida: " + e);
    }
    sslContext = sslContexts.get(bundleKey);

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.SSL)) {
        isSslEnabled = true;
        if (sslContext == null) {
            try {
                FileInputStream finKeyStore = null;
                FileInputStream finTrustStore = null;

                KeyManager[] km = null;
                TrustManager[] tm = null;

                // Autenticazione CLIENT
                if (connettore.getTipoSsl().equals(EnumSslType.CLIENT)) {

                    if (connettore.getSslKsType() == null || connettore.getSslKsLocation() == null
                            || connettore.getSslKsPasswd() == null || connettore.getSslPKeyPasswd() == null)
                        throw new ClientException(
                                "Configurazione SSL Client del connettore " + errMsg + " incompleta.");

                    KeyStore keystore = KeyStore.getInstance(connettore.getSslKsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                    finKeyStore = new FileInputStream(connettore.getSslKsLocation());
                    keystore.load(finKeyStore, connettore.getSslKsPasswd().toCharArray());
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManagerFactory.init(keystore, connettore.getSslPKeyPasswd().toCharArray());
                    km = keyManagerFactory.getKeyManagers();
                }

                if (connettore.getSslTsType() == null || connettore.getSslTsLocation() == null
                        || connettore.getSslTsPasswd() == null || connettore.getSslType() == null)
                    throw new ClientException(
                            "Configurazione SSL Server del connettore " + errMsg + " incompleta.");

                // Autenticazione SERVER
                KeyStore truststore = KeyStore.getInstance(connettore.getSslTsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                finTrustStore = new FileInputStream(connettore.getSslTsLocation());
                truststore.load(finTrustStore, connettore.getSslTsPasswd().toCharArray());
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(truststore);
                tm = trustManagerFactory.getTrustManagers();

                // Creo contesto SSL
                sslContext = SSLContext.getInstance(connettore.getSslType());
                sslContext.init(km, tm, null);
                sslContexts.put(bundleKey, sslContext);
            } catch (Exception e) {
                throw new ClientException(e);
            }
        }
    }

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.HTTPBasic)) {
        ishttpBasicEnabled = true;
        httpBasicUser = connettore.getHttpUser();
        httpBasicPassword = connettore.getHttpPassw();
    }
}

From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//ww w. jav a2 s  .  com
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName/*from   www  .j a  va 2 s .  co  m*/
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:com.centeractive.ws.client.core.SoapClient.java

private void configureTls() {
    if (tlsEnabled == false) {
        return;//from w w w . ja v  a2 s . c  om
    }
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        context = SSLContext.getInstance(sslContextProtocol);
        context.init(null, new TrustManager[] { defaultTrustManager }, null);
        sslSocketFactory = context.getSocketFactory();
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        if (strictHostVerification == false) {
            ((HttpsURLConnection) connection).setHostnameVerifier(new SoapHostnameVerifier());
        }
    } catch (GeneralSecurityException e) {
        throw new SoapClientException("TLS/SSL setup failed", e);
    }
}