Example usage for javax.net.ssl TrustManagerFactory init

List of usage examples for javax.net.ssl TrustManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory init.

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.wso2.carbon.inbound.ibmmq.poll.IbmMqConsumer.java

public void sslConnection() {
    String keyStoreLocation = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_LOCATION);
    String keyStoreType = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_TYPE);
    String keyStorePassword = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_PASSWORD);
    String trustStoreLocation = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_LOCATION);
    String trustStoreType = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_TYPE);
    String sslVersion = properties.getProperty(ibmMqConstant.SSL_VERSION);
    String sslFipsRequired = properties.getProperty(ibmMqConstant.SSL_FIPS);
    String sslCipherSuite = properties.getProperty(ibmMqConstant.SSL_CIPHERSUITE);
    boolean sslFips = Boolean.parseBoolean(sslFipsRequired);
    try {//w  w  w  .  jav a2s  .co  m
        char[] keyPassphrase = keyStorePassword.toCharArray();
        KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);
        trustStore.load(new FileInputStream(trustStoreLocation), null);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(trustStore);
        keyManagerFactory.init(ks, keyPassphrase);
        SSLContext sslContext = SSLContext.getInstance(sslVersion);
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        MQEnvironment.sslSocketFactory = sslContext.getSocketFactory();
        MQEnvironment.sslFipsRequired = sslFips;
        MQEnvironment.sslCipherSuite = sslCipherSuite;
    } catch (Exception ex) {
        handleException(ex.getMessage());
    }
}

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:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@After
// Clean up the credentialManagerDirectory we created for testing
public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException,
        KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    //      assertTrue(credentialManagerDirectory.exists());
    //      assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there

    if (credentialManagerDirectory.exists()) {
        try {/*from  www .j a  va2s  . c  o  m*/
            FileUtils.deleteDirectory(credentialManagerDirectory);
            System.out.println(
                    "Deleting Credential Manager's directory: " + credentialManagerDirectory.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // Reset the SSLSocketFactory in JVM so we always have a clean start
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSLv3");

    // Create a "default" JSSE X509KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    kmf.init(ks, "blah".toCharArray());

    // Create a "default" JSSE X509TrustManager.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(null, null);
    tmf.init(ts);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:com.alliander.osgp.shared.usermanagement.OrganisationManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation/*from w ww  .  j ava2 s . c  o m*/
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws OrganisationManagementClientException
 *             In case the construction fails, a
 *             OrganisationManagementClientException will be thrown.
 */
public OrganisationManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws OrganisationManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code TrustManagerFactory} from provided
 * {@code KeyStore}./*from   www . jav a 2s  . c  o  m*/
 * 
 * @param keyStore
 *            the KeyStore to get the TrustManagerFactory
 * @return the new {@code TrustManagerFactory} instance.
 * @throws KeyStoreException
 *             if an error occurred during the creation of the new KeyStore.
 * @throws NoSuchAlgorithmException
 *             if the required algorithm is not available.
 * 
 */
private TrustManagerFactory getTrustManager(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {
    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);
    return tmf;
}

From source file:org.wso2.carbon.identity.core.util.ClientAuthX509TrustManager.java

/**
 * This method reloads the TrustManager by reading the carbon server's default trust store file
 *
 * @throws Exception/*from  w  w  w. j  av  a2  s .  co m*/
 */
private void setupTrustManager() throws Exception {

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore clientTrustStore;
    try (InputStream trustStoreInputStream = new FileInputStream(TRUST_STORE_LOCATION)) {

        clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
        clientTrustStore.load(trustStoreInputStream, null);

        trustManagerFactory.init(clientTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        for (TrustManager t : trustManagers) {
            if (t instanceof X509TrustManager) {
                trustManager = (X509TrustManager) t;
                System.setProperty(PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
                return;
            }
        }
        throw new IdentityException("No X509TrustManager in TrustManagerFactory");
    }
}

From source file:com.quarterfull.newsAndroid.ssl.MemorizingTrustManager.java

X509TrustManager getTrustManager(KeyStore ks) {
    try {/*from w w w.j a  v  a  2 s .  c  o m*/
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);
        for (TrustManager t : tmf.getTrustManagers()) {
            if (t instanceof X509TrustManager) {
                return (X509TrustManager) t;
            }
        }
    } catch (Exception e) {
        // Here, we are covering up errors. It might be more useful
        // however to throw them out of the constructor so the
        // embedding app knows something went wrong.
        Log.e(TAG, "getTrustManager(" + ks + ")", e);
    }
    return null;
}

From source file:org.wso2.carbon.identity.core.util.DynamicX509TrustManager.java

/**
 * This method reloads the TrustManager by reading the carbon server's default trust store file
 *
 * @throws Exception//from   w  w  w  .j  a  v a2s.c o  m
 */
private void setupTrustManager() throws Exception {

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore clientTrustStore = null;
    try (InputStream trustStoreInputStream = new FileInputStream(TRUST_STORE_LOCATION)) {

        clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
        clientTrustStore.load(trustStoreInputStream, null);
        trustManagerFactory.init(clientTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        for (TrustManager t : trustManagers) {
            if (t instanceof X509TrustManager) {
                trustManager = (X509TrustManager) t;
                System.setProperty(IdentityUtil.PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
                return;
            }
        }
        throw new IdentityException("No X509TrustManager in TrustManagerFactory");
    }
}

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 w  w  w  .java  2  s . co m*/
            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);
    }
}