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.apache.cassandra.hadoop.cql3.CqlConfigHelper.java

private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    SSLContext ctx;/*from   w  w w .  j  a  va 2  s  .c o  m*/
    try (FileInputStream tsf = new FileInputStream(truststorePath);
            FileInputStream ksf = new FileInputStream(keystorePath)) {
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    }
    return ctx;
}

From source file:org.apache.geode.internal.net.SocketCreator.java

private TrustManager[] getTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    TrustManager[] trustManagers = null;
    GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

    String trustStoreType = sslConfig.getTruststoreType();
    if (StringUtils.isEmpty(trustStoreType)) {
        // read from console, default on empty
        if (consoleReader.isSupported()) {
            trustStoreType = consoleReader
                    .readLine("Please enter the trustStoreType (javax.net.ssl.trustStoreType) : ");
        } else {/*from   w w w  .  ja  va 2  s.co m*/
            trustStoreType = KeyStore.getDefaultType();
        }
    }

    KeyStore ts = KeyStore.getInstance(trustStoreType);
    String trustStorePath = sslConfig.getTruststore();
    if (StringUtils.isEmpty(trustStorePath)) {
        if (consoleReader.isSupported()) {
            trustStorePath = consoleReader
                    .readLine("Please enter the trustStore location (javax.net.ssl.trustStore) : ");
        }
    }
    FileInputStream fis = new FileInputStream(trustStorePath);
    String passwordString = sslConfig.getTruststorePassword();
    char[] password = null;
    if (passwordString != null) {
        if (passwordString.trim().equals("")) {
            if (!StringUtils.isEmpty(passwordString)) {
                String toDecrypt = "encrypted(" + passwordString + ")";
                passwordString = PasswordUtil.decrypt(toDecrypt);
                password = passwordString.toCharArray();
            }
            // read from the console
            if (StringUtils.isEmpty(passwordString) && consoleReader.isSupported()) {
                password = consoleReader.readPassword(
                        "Please enter password for trustStore (javax.net.ssl.trustStorePassword) : ");
            }
        } else {
            password = passwordString.toCharArray();
        }
    }
    ts.load(fis, password);

    // default algorithm can be changed by setting property "ssl.TrustManagerFactory.algorithm" in
    // security properties
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);
    trustManagers = tmf.getTrustManagers();
    // follow the security tip in java doc
    if (password != null) {
        java.util.Arrays.fill(password, ' ');
    }

    return trustManagers;
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;//from   w ww.  j  av a2s. co  m
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;// www  .  j  av  a2s .co m
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}

From source file:org.apache.geode.management.internal.cli.commands.ConnectCommand.java

private TrustManager[] getTrustManagers(SSLConfig sslConfig, boolean skipSslVerification) throws Exception {
    FileInputStream trustStoreStream = null;
    TrustManagerFactory trustManagerFactory = null;

    if (skipSslVerification) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }/*  ww  w  .  j a  va2  s  . c om*/

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }

        } };
        return trustAllCerts;
    }

    try {
        // load server public key
        if (StringUtils.isNotBlank(sslConfig.getTruststore())) {
            KeyStore serverPub = KeyStore.getInstance(sslConfig.getTruststoreType());
            trustStoreStream = new FileInputStream(sslConfig.getTruststore());
            serverPub.load(trustStoreStream, sslConfig.getTruststorePassword().toCharArray());
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(serverPub);
        }
    } finally {
        if (trustStoreStream != null) {
            trustStoreStream.close();
        }
    }
    return trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null;
}

From source file:com.datastax.loader.CqlDelimLoad.java

private SSLOptions createSSLOptions() throws KeyStoreException, FileNotFoundException, IOException,
        NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    TrustManagerFactory tmf = null;
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load((InputStream) new FileInputStream(new File(truststorePath)), truststorePwd.toCharArray());
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);// w w  w .java 2 s  . c  o m

    KeyManagerFactory kmf = null;
    if (null != keystorePath) {
        KeyStore kks = KeyStore.getInstance("JKS");
        kks.load((InputStream) new FileInputStream(new File(keystorePath)), keystorePwd.toCharArray());
        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(kks, keystorePwd.toCharArray());
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
            new SecureRandom());

    return JdkSSLOptions.builder().withSSLContext(sslContext).build();
}

From source file:org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl.java

/**
 * Initializes the SSL Context// w ww .  j av  a  2  s.co m
 */
private void initSSLConnection()
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
}

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());
    }/*from   w ww .j av  a  2s. c om*/

    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:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) {
    HttpsURLConnection urlConnection = conn;
    try {/*from  ww w  .  ja  v  a2 s  .  com*/
        KeyStore localTrustStore;

        localTrustStore = KeyStore.getInstance("BKS");

        InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);

        localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

        TrustManagerFactory tmf;
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        tmf.init(localTrustStore);

        SSLContext sslCtx;

        sslCtx = SSLContext.getInstance("TLS");

        sslCtx.init(null, tmf.getTrustManagers(), null);

        urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());
        return urlConnection;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return null;
    }

}