Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

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

Introduction

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

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

protected final void createUnmanagedFactory(SslParameters ssl) throws Exception {
    SSLContext context;//from w  w  w.j ava 2  s  . c  o m
    if (ssl.getProvider() == null) {
        context = SSLContext.getInstance(ssl.getProtocol());
    } else {
        context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider());
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm());
    String keyStore = ssl.getKeyStore();
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
        if (keyStore == null) {
            throw new IllegalArgumentException(
                    "keyStore or system property javax.net.ssl.keyStore must be set");
        }
    }
    if (keyStore.startsWith("classpath:")) {
        try {
            String res = keyStore.substring(10);
            URL url = new ClassPathResource(res).getURL();
            keyStore = url.toString();
        } catch (IOException e) {
            throw new JBIException("Unable to find keyStore " + keyStore, e);
        }
    }
    String keyStorePassword = ssl.getKeyStorePassword();
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (keyStorePassword == null) {
            throw new IllegalArgumentException(
                    "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
        }
    }
    String trustStore = ssl.getTrustStore();
    String trustStorePassword = null;
    if (trustStore == null) {
        trustStore = System.getProperty("javax.net.ssl.trustStore");
    }
    if (trustStore != null) {
        if (trustStore.startsWith("classpath:")) {
            try {
                String res = trustStore.substring(10);
                URL url = new ClassPathResource(res).getURL();
                trustStore = url.toString();
            } catch (IOException e) {
                throw new JBIException("Unable to find trustStore " + trustStore, e);
            }
        }
        trustStorePassword = ssl.getTrustStorePassword();
        if (trustStorePassword == null) {
            trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword == null) {
                throw new IllegalArgumentException(
                        "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
            }
        }
    }
    KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType());
    ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
    keyManagerFactory.init(ks,
            ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray());
    if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType());
        ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(ssl.getTrustManagerFactoryAlgorithm());
        trustManagerFactory.init(ts);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new java.security.SecureRandom());
    } else {
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());
    }
    factory = context.getSocketFactory();
}

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./*  www  . j a  v  a 2  s.  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:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLSender.java

protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault {

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

    Parameter keyParam = transportOut.getParameter("keystore");
    Parameter trustParam = transportOut.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        try {/*w w w  .j a v a2s.  c om*/
            KeyStore keyStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Key Store from URL : " + url);

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

        } 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);
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();

        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Trust Key Store from URL : " + url);

            trustStore.load(url.openStream(), 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);
        }
    }

    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:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {/*from  w  ww . jav  a2  s  . c om*/
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.wildfly.elytron.web.undertow.server.ClientCertAuthenticationTest.java

/**
 * Get the trust manager that trusts all certificates signed by the certificate authority.
 *
 * @return the trust manager that trusts all certificates signed by the certificate authority.
 * @throws KeyStoreException//from ww  w . ja va2s.  co  m
 */
private X509TrustManager getCATrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore("/tls/ca.truststore"));

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

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

From source file:com.openshift.restclient.ClientBuilder.java

private X509TrustManager getCurrentTrustManager(TrustManagerFactory trustManagerFactory)
        throws NoSuchAlgorithmException, KeyStoreException {
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
            return new CallbackTrustManager(x509TrustManager, this.sslCertificateCallback);
        }/* w  w  w  . j  a  v  a 2s  .  co  m*/
    }
    return null;

}

From source file:org.apache.camel.component.file.remote.FtpsEndpoint.java

/**
 * Create the FTPS client.//from ww w.j a va 2  s.c  o m
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}

From source file:org.lockss.util.urlconn.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws IOException {
    LockssDaemon daemon = LockssDaemon.getLockssDaemon();
    LockssKeyStoreManager keystoreMgr;// www  .  j  ava2 s  .  c om
    SecureRandom rng;
    try {
        if (daemon.isDaemonRunning()) {
            keystoreMgr = daemon.getKeystoreManager();
            RandomManager rmgr = daemon.getRandomManager();
            rng = rmgr.getSecureRandom();
        } else {
            rng = getSecureRandom();
            keystoreMgr = new LockssKeyStoreManager();
            keystoreMgr.initService(daemon);
            keystoreMgr.startService();
            Configuration platConfig = ConfigManager.getPlatformConfig();
            keystoreMgr.setConfig(platConfig, null, platConfig.differences(null));
        }
        KeyManager[] kma = null;
        if (privateKeyStoreName != null) {
            KeyManagerFactory kmf = keystoreMgr.getKeyManagerFactory(privateKeyStoreName, "ClientAuth");
            if (kmf != null) {
                kma = kmf.getKeyManagers();
            } else if (false) {
                throw new IllegalArgumentException("Private keystore not found: " + privateKeyStoreName);
            }
        }
        TrustManager[] tma = null;
        if (publicKeyStoreName != null) {
            TrustManagerFactory tmf = keystoreMgr.getTrustManagerFactory(publicKeyStoreName, "ServerAuth");
            if (tmf != null) {
                tma = tmf.getTrustManagers();
            } else if (false) {
                throw new IllegalArgumentException("Public keystore not found: " + publicKeyStoreName);
            }
        }
        // Now create an SSLContext from the KeyManager
        SSLContext ctxt = null;
        ctxt = SSLContext.getInstance(sslProtocol); // "SSL"
        ctxt.init(kma, tma, rng);
        log.debug2("createSSLContext: " + ctxt);
        hasKeyManagers = kma != null && kma.length != 0;
        hasTrustManagers = tma != null && tma.length != 0;
        return ctxt;
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException("Can't create SSL Context", ex);
    } catch (NoSuchProviderException ex) {
        throw new IOException("Can't create SSL Context", ex);
    } catch (KeyManagementException ex) {
        throw new IOException("Can't create SSL Context", ex);
    }
}

From source file:org.opendaylight.aaa.cert.impl.CertificateManagerService.java

@Override
public SSLContext getServerContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*w ww  . j  ava 2s. c  o m*/
    SSLContext serverContext = null;
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(aaaCertProvider.getODLKeyStore(),
                aaaCertProvider.getOdlKeyStoreInfo().getStorePassword().toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init(aaaCertProvider.getTrustKeyStore());

        serverContext = SSLContext.getInstance(KeyStoreConstant.TLS_PROTOCOL);
        serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (final NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException
            | KeyManagementException e) {
        LOG.error("Error while creating SSLContext ", e);
    }
    return serverContext;
}

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

/**
 * Create the SSLContext to be used by this listener
 * @param transportIn the Axis2 transport description
 * @return the SSLContext to be used// w ww  .  j  a va 2 s.c  o  m
 */
protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {

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

    Parameter keyParam = transportIn.getParameter("keystore");
    Parameter trustParam = transportIn.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {
            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 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) {
                }
            }
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.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) {
                }
            }
        }
    }

    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);
    }
}