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:AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  ww  w  . j av a  2  s  . c om*/
    System.out.println("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName/*www  .  j ava 2s  . c o  m*/
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}

From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java

private static TrustManager[] createTrustManagers(String trustStoreType, String trustStorePath,
        String trustStorePassword) throws Exception {
    KeyStore trustStore = loadKeyStore(trustStoreType, trustStorePath, trustStorePassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);//from  w  ww  .j a  v  a2 s .c  o  m
    return tmf.getTrustManagers();
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*  w w  w .  j av a 2 s . c  o  m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream inputStream = trustFile.getInputStream()) {
        trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }//ww  w  .java 2  s  . c o  m

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

    return trustManagerFactory;
}

From source file:org.mitre.svmp.net.SSLConfig.java

@SuppressLint("TrulyRandom")
private void doConfigure() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException {
    // find out if we should use the MemorizingTrustManager instead of the system trust store (set in Preferences)
    boolean useMTM = Utility.getPrefBool(context, R.string.preferenceKey_connection_useMTM,
            R.string.preferenceValue_connection_useMTM);

    // determine whether we should use client certificate authentication
    boolean useCertificateAuth = Constants.API_14 && (connectionInfo.getAuthType()
            & CertificateModule.AUTH_MODULE_ID) == CertificateModule.AUTH_MODULE_ID;

    // set up key managers
    KeyManager[] keyManagers = null;
    // if certificate authentication is enabled, use a key manager with the provided alias
    if (useCertificateAuth) {
        keyManagers = new KeyManager[] { new SVMPKeyManager(context, connectionInfo.getCertificateAlias()) };
    }//from  w w  w . j  a  v  a 2  s .  c o m

    // set up trust managers
    TrustManager[] trustManagers = null;

    KeyStore localTrustStore = KeyStore.getInstance("BKS");
    InputStream in = context.getResources().openRawResource(R.raw.client_truststore);
    localTrustStore.load(in, Constants.TRUSTSTORE_PASSWORD.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(localTrustStore);

    // 1) If "res/raw/client_truststore.bks" is not empty, use it as the pinned cert trust store (default is empty)
    // 2) Otherwise, if the "Show certificate dialog" developer preference is enabled, use that (default is disabled)
    // 3) Otherwise, use the default system trust store, consists of normal trusted Android CA certs
    if (localTrustStore.size() > 0) {
        // this means that "res/raw/client_truststore.bks" has been replaced with a trust store that is not empty
        // we will use that "pinned" store to check server certificate trust
        Log.d(TAG, "SSLConfig: Using static BKS trust store to check server cert trust");
        trustManagers = trustManagerFactory.getTrustManagers();
        // After switching to WebSockets, MTM causes the app to freeze; removed for now
    } else if (useMTM) {
        // by default useMTM is false ("Show certificate dialog" in developer preferences)
        // this creates a certificate dialog to decide what to do with untrusted certificates, instead of flat-out rejecting them
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty but MTM is enabled, using MTM to check server cert trust");
        mtm = new MemorizingTrustManager(context);
        mtm.bindDisplayActivity(activity);
        trustManagers = new X509TrustManager[] { mtm };
    } else {
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty and MTM is disabled, using system trust store to check server cert trust");
        // leaving trustManagers null accomplishes this
    }

    PRNGFixes.apply(); // fix Android SecureRandom issue on pre-KitKat platforms
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, new SecureRandom());
}

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;//from   w  ww  .j  av  a2s .  com

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

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

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

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}

From source file:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

@Override
public TLSClientParameters getTLSParameters() {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {/* ww w .  ja va2  s. c o m*/
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.warn(
                "Could not fully load keystore/truststore into TLSParameters. Parameters may not be fully functional.",
                e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

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 {//from   ww  w .  j  a v  a2  s .  c o  m
            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:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server./*from  w  ww.  ja  va 2 s  .  c o  m*/
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}