Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

List of usage examples for javax.net.ssl KeyManagerFactory getKeyManagers

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getKeyManagers.

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

/**
 * {@inheritDoc}/*from  www.j a v  a2 s . c  om*/
 */
@Override
public KeyManager[] createKeyManagers() {
    KeyInfoManager keyInfoManager = null;

    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(keyStoreParameters, keyInfoManager);

        logger.debug("Initializing key managers");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        String keyStorePassword = keyInfoManager.getKeyStorePassword();
        kmfactory.init(ks, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
        return kmfactory.getKeyManagers();
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }
    }
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory//from   w  ww . j av  a 2s . c o  m
 */
private 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(
                            "Trustore 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:org.apache.geode.management.internal.cli.commands.ConnectCommand.java

private KeyManager[] getKeyManagers(SSLConfig sslConfig) throws Exception {
    FileInputStream keyStoreStream = null;
    KeyManagerFactory keyManagerFactory = null;

    try {//from  w  w  w.jav  a  2  s  . c  om
        if (StringUtils.isNotBlank(sslConfig.getKeystore())) {
            KeyStore clientKeys = KeyStore.getInstance(sslConfig.getKeystoreType());
            keyStoreStream = new FileInputStream(sslConfig.getKeystore());
            clientKeys.load(keyStoreStream, sslConfig.getKeystorePassword().toCharArray());

            keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeys, sslConfig.getKeystorePassword().toCharArray());
        }
    } finally {
        if (keyStoreStream != null) {
            keyStoreStream.close();
        }
    }

    return keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null;
}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }/*  w w w .  ja  v  a2  s .c  o  m*/

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
    trustManagerFactory.init(truststore);

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);//from  ww w  . j a v  a2s  . c o  m

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

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

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

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;// ww w.j  a  v 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:org.nectarframework.base.service.nanohttp.NanoHttpService.java

/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase/*from   w w  w.  ja v a2  s.c o m*/
 */
public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase)
        throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath));

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);

        SSLServerSocketFactory res = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            res = ctx.getServerSocketFactory();

        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }

        SSLServerSocket ss = null;
        ss = (SSLServerSocket) res.createServerSocket();
        ss.setEnabledProtocols(ss.getSupportedProtocols());
        ss.setUseClientMode(false);
        ss.setWantClientAuth(false);
        ss.setNeedClientAuth(false);

        return ss;

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.deviceconnect.android.message.DevicePluginContext.java

/**
 * SSLContext ?????.//from w  w w . j  a v a2s  .c  o m
 * <p>
 * ? Web ?????Manager???????????SSLContext ???
 * </p>
 * @param keyStore 
 * @return SSLContext?
 * @throws GeneralSecurityException SSLContext???????
 */
protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, "0000".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *//*  w ww  . j  a v  a 2 s. c om*/
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: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  www  .  j  a  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);
        }
    }
}