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: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. j  av  a2  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.wso2.carbon.extension.analytics.receiver.rabbitmq.internal.util.RabbitMQAdapterListener.java

public RabbitMQAdapterListener(RabbitMQBrokerConnectionConfiguration rabbitmqBrokerConnectionConfiguration,
        InputEventAdapterConfiguration eventAdapterConfiguration,
        InputEventAdapterListener inputEventAdapterListener) {

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

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    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 c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } 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(RabbitMQEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT))) {
        try {
            int heartbeatValue = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT));
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    connectionFactory.setHost(rabbitmqBrokerConnectionConfiguration.getHostName());
    try {
        int port = Integer.parseInt(rabbitmqBrokerConnectionConfiguration.getPort());
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }
    connectionFactory.setUsername(rabbitmqBrokerConnectionConfiguration.getUsername());
    connectionFactory.setPassword(rabbitmqBrokerConnectionConfiguration.getPassword());
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST))) {
        connectionFactory.setVirtualHost(eventAdapterConfiguration.getProperties()
                .get(RabbitMQEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST));
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT))) {
        try {
            retryCountMax = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.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(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL))) {
        try {
            retryInterval = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.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:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Builds an SSLConect that trusts the trust material in the KeyStore
 *
 * @param trustMaterial// w  w w.  ja va 2  s .  c  o  m
 * @return
 */
public static SSLContext buildContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);

        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

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

    return ctx;
}

From source file:org.wisdom.engine.ssl.SSLServerContext.java

private TrustManagerFactory getTrustManagerFactoryFromKeyStore(final File maybeRoot, final String path)
        throws KeyStoreException {
    final TrustManagerFactory tmf;
    File file = new File(path);
    if (!file.isFile()) {
        // Second chance.
        file = new File(maybeRoot, path);
    }/*from  w  w  w  . j  av  a  2s .  co m*/

    LOGGER.info("\t trust store: " + file.getAbsolutePath());
    final KeyStore trustStore = KeyStore
            .getInstance(accessor.getConfiguration().getWithDefault("https.trustStoreType", "JKS"));
    LOGGER.info("\t trust store type: " + trustStore.getType());
    LOGGER.info("\t trust store provider: " + trustStore.getProvider());
    final char[] password = accessor.getConfiguration().getWithDefault("https.trustStorePassword", "")
            .toCharArray();
    LOGGER.info("\t trust store password length: " + password.length);
    final String algorithm = accessor.getConfiguration().getWithDefault("https.trustStoreAlgorithm",
            KeyManagerFactory.getDefaultAlgorithm());
    LOGGER.info("\t trust store algorithm: " + algorithm);
    if (file.isFile()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            trustStore.load(stream, password);
            tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(trustStore);
        } catch (final Exception e) {
            throw new RuntimeException(HTTPSFAIL + e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    } else {
        throw new RuntimeException(
                "Cannot load trust store from '" + file.getAbsolutePath() + "', " + "the file does not exist");
    }
    return tmf;
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public void sendRequest(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, KeyManagementException {

    //log.info("Sending to RapidSMS:\n" + msg);

    // Get the key store that includes self-signed cert as a "trusted"
    // entry./*from  www  . j a v  a2s . c  o m*/
    InputStream keyStoreStream = org.mule.util.IOUtils.getResourceAsStream("truststore.jks",
            GenerateORU_R01Alert.class);

    // Load the keyStore

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    //log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
    keyStoreStream.close();

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

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();

    callQueryFacility(msg);

}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

private TrustManager[] createTrustManagers(final KeyStore trustStore)
        throws NoSuchAlgorithmException, KeyStoreException {
    if (trustStore == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but trust store is null");
        throw new IllegalArgumentException("TrustStore cannot be null");
    }/*from  w w w  .  j av  a2s  . co m*/
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    return tmf.getTrustManagers();
}

From source file:org.apache.activemq.ActiveMQSslConnectionFactoryTest.java

public static TrustManager[] getTrustManager() throws Exception {
    TrustManager[] trustStoreManagers = null;
    KeyStore trustedCertStore = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE);

    trustedCertStore.load(new FileInputStream(ActiveMQSslConnectionFactoryTest.TRUST_KEYSTORE), null);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(trustedCertStore);/* w  ww.jav a 2 s . c o  m*/
    trustStoreManagers = tmf.getTrustManagers();
    return trustStoreManagers;
}