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:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java

public void initMemoryTrustManager(boolean forcereload)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    if (memoryTrustManager != null && !forcereload) {
        return;//  w  ww  .  j ava2  s . c  om
    }
    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.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from   w w  w  . j a  v  a  2 s  . c o  m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    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, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(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 | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

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 ww w  . java 2 s  .  com

        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 initPersistedTrustManager(boolean forcereload)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    if (persistedTrustManager != null && !forcereload) {
        return;/*from  w  w  w.  j av a2  s  .c  om*/
    }

    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: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   www . jav a 2  s .c om*/

    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.wso2.carbon.inbound.endpoint.protocol.mqtt.MqttConnectionFactory.java

protected SSLSocketFactory getSocketFactory(String keyStoreLocation, String keyStoreType,
        String keyStorePassword, String trustStoreLocation, String trustStoreType, String trustStorePassword,
        String sslVersion) throws Exception {

    char[] keyPassphrase = keyStorePassword.toCharArray();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(new FileInputStream(keyStoreLocation), keyPassphrase);

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

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

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    SSLContext sslContext = SSLContext.getInstance(sslVersion);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}

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/* www .ja  v  a2s .  c o m*/
 * @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:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code SSLContext} from the given
 * {@code TrustManagerFactory} {@code tmf}.
 * /* w w w.ja v a2s.  c  om*/
 * @param tmf
 *            the TrustManagerFactory to create a SSLContext
 * @return the new {@code SSLContext} instance.
 * @throws NoSuchAlgorithmException
 *             if the required algorithm is not available.
 * @throws KeyManagementException
 *             if initializing this instance fails.
 */
private SSLContext getSSLContext(TrustManagerFactory tmf)
        throws NoSuchAlgorithmException, KeyManagementException {

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
}

From source file:org.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java

protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl,
        final OMElement cientAuthEl, final OMElement httpsProtocolsEl,
        final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    if (keyStoreEl != null) {
        String location = getValueOfElementWithLocalName(keyStoreEl, "Location");
        String type = getValueOfElementWithLocalName(keyStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password");
        String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword");

        FileInputStream fis = null;
        try {//from   w w  w . j a v a2  s .c  o  m
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Identity Keystore from : " + location);
            }

            keyStore.load(fis, storePassword.toCharArray());

            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
            if (log.isInfoEnabled() && keymanagers != null) {
                for (KeyManager keymanager : keymanagers) {
                    if (keymanager instanceof X509KeyManager) {
                        X509KeyManager x509keymanager = (X509KeyManager) keymanager;
                        Enumeration<String> en = keyStore.aliases();
                        while (en.hasMoreElements()) {
                            String s = en.nextElement();
                            X509Certificate[] certs = x509keymanager.getCertificateChain(s);
                            if (certs == null)
                                continue;
                            for (X509Certificate cert : certs) {
                                log.debug(name + " Subject DN: " + cert.getSubjectDN());
                                log.debug(name + " Issuer DN: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreEl != null) {
        String location = getValueOfElementWithLocalName(trustStoreEl, "Location");
        String type = getValueOfElementWithLocalName(trustStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password");

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Trust Keystore from : " + location);
            }

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
    final String s = cientAuthEl != null ? cientAuthEl.getText() : null;
    final SSLClientAuth clientAuth;
    if ("optional".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.OPTIONAL;
    } else if ("require".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.REQUIRED;
    } else {
        clientAuth = null;
    }

    String[] httpsProtocols = null;
    final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null;
    if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) {
        String[] configuredValues = configuredHttpsProtocols.trim().split(",");
        List<String> protocolList = new ArrayList<String>(configuredValues.length);
        for (String protocol : configuredValues) {
            if (!protocol.trim().isEmpty()) {
                protocolList.add(protocol.trim());
            }
        }

        httpsProtocols = protocolList.toArray(new String[protocolList.size()]);
    }

    try {
        final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS";
        SSLContext sslContext = SSLContext.getInstance(sslProtocolValue);
        sslContext.init(keymanagers, trustManagers, null);

        ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null)
                ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager)
                : null;

        return new SSLContextDetails(sslContext, sslSetupHandler);
    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}