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:org.asynchttpclient.test.TestUtils.java

private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStoreStream = TestUtils.class.getClassLoader()
            .getResourceAsStream("ssltest-keystore.jks")) {
        char[] keyStorePassword = "changeit".toCharArray();
        ks.load(keyStoreStream, keyStorePassword);
    }//from w w w  .  j a va2  s. c o m
    assert (ks.size() > 0);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort, KeyStore keyStore) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);/*  ww w. j a  v a 2 s.co m*/
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLSender.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

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

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {/*from www.j av a2  s .  c om*/
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Identity Keystore from : " + location);

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

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

    if (trustStoreElt != null) {
        if (novalidatecert) {
            log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("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("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("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) {
                }
            }
        }
    } else if (novalidatecert) {
        log.warn("Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!");
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

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

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.ExternalMgmtSaslTestCase.java

/**
 * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}.
 *
 * @return the trust manager/*from   w w  w .  j  a  va  2  s .  c om*/
 */
private static X509TrustManager getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}

From source file:org.pentaho.di.trans.steps.rest.Rest.java

private void setConfig() throws KettleException {

    if (data.config == null) {
        // Use ApacheHttpClient for supporting proxy authentication.
        data.config = new DefaultApacheHttpClientConfig();

        if (!Const.isEmpty(data.realProxyHost)) {
            // PROXY CONFIGURATION
            data.config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI,
                    "http://" + data.realProxyHost + ":" + data.realProxyPort);
            if (!Const.isEmpty(data.realHttpLogin) && !Const.isEmpty(data.realHttpPassword)) {
                data.config.getState().setProxyCredentials(AuthScope.ANY_REALM, data.realProxyHost,
                        data.realProxyPort, data.realHttpLogin, data.realHttpPassword);
            }//  w w  w. jav a  2  s  .co m
        } else {
            if (!Const.isEmpty(data.realHttpLogin)) {
                // Basic authentication
                data.basicAuthentication = new HTTPBasicAuthFilter(data.realHttpLogin, data.realHttpPassword);
            }
        }
        if (meta.isPreemptive()) {
            data.config.getProperties().put(ApacheHttpClientConfig.PROPERTY_PREEMPTIVE_AUTHENTICATION, true);
        }

        // SSL TRUST STORE CONFIGURATION
        if (!Const.isEmpty(data.trustStoreFile)) {

            try {
                KeyStore trustStore = KeyStore.getInstance("JKS");
                trustStore.load(new FileInputStream(data.trustStoreFile),
                        data.trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(trustStore);

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

                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        if (isDebug()) {
                            logDebug("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
                        }
                        return true;
                    }
                };

                data.config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(hv, ctx));

            } catch (NoSuchAlgorithmException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.NoSuchAlgorithm"), e);
            } catch (KeyStoreException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyStoreException"), e);
            } catch (CertificateException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.CertificateException"), e);
            } catch (FileNotFoundException e) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Rest.Error.FileNotFound", data.trustStoreFile), e);
            } catch (IOException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.IOException"), e);
            } catch (KeyManagementException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyManagementException"), e);
            }
        }

    }
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;/*w w w.ja va 2s.c o  m*/
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(truststore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            /*
             * @TODO: I need to uncomment the 3 lines below. TrustManagerDecorator is not public (package visibility)
             */
            // if (tm instanceof X509TrustManager) {
            //    trustmanagers[i] = new TrustManagerDecorator(
            //            (X509TrustManager) tm, trustStrategy);
            //}
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}

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

/**
 * Initialize connection factory/*from ww  w . ja va  2s . co 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.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory/*ww w  . j av a 2 s.  c o  m*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:de.fun2code.google.cloudprint.push.PushReceiver.java

/**
 * Sets up the SSL socket for use with XMPP.
 * /*from   w  w  w.  j a  va2s.c  om*/
 * @param socket
 *            the socket to do TLS over.
 * @return   The SSL Socket.
 * @throws IOException
 */
public static SSLSocket setupSSLSocket(Socket socket) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException, IOException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustManagerFactory tfactory = TrustManagerFactory.getInstance("SunPKIX");
    tfactory.init(keyStore);
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket.getInetAddress().getHostAddress(),
            socket.getPort(), true);
    sslsocket.setUseClientMode(true);
    return sslsocket;
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedProtocolSocketFactory.java

/**
 * Adds the given truststore to the existing default JSSE {@link TrustManager}.
 * /*from   w w w .j a v a2  s . c om*/
 * @param truststore The truststore to add to the list.
 * @return An array of {@link TrustManager}
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private TrustManager[] createExtendedTrustManagers(KeyStore truststore)
        throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException {
    if (truststore == null) {
        throw new IllegalArgumentException("Truststore may not be null");
    }
    LOG.debug("Initializing TrustManager");
    // initialize with the JSSE default trustStore
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init((KeyStore) null);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    // extend the default TrustManager
    // LOG.debug("default JSSE TrustManager# " + trustmanagers.length);
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            LOG.debug("Installing the ExtendedTrustX509TrustManager");
            trustmanagers[i] = new ExtendedX509TrustManager(truststore, (X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}