List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:com.njlabs.amrita.aid.gpms.ui.GpmsActivity.java
public Picasso getUnsecuredPicassoDownloader() { try {// w w w . j a v a 2 s .c om TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); Picasso.Builder builder = new Picasso.Builder(baseContext).listener(new Picasso.Listener() { @Override public void onImageLoadFailed(Picasso arg0, Uri arg1, Exception ex) { ex.printStackTrace(); } }); OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sc.getSocketFactory()) .hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).build(); Downloader downloader = new OkHttp3Downloader(client); return builder.downloader(downloader).build(); } catch (Exception ignored) { Picasso.Builder builder = new Picasso.Builder(baseContext).listener(new Picasso.Listener() { @Override public void onImageLoadFailed(Picasso arg0, Uri arg1, Exception ex) { ex.printStackTrace(); } }); return builder.build(); } }
From source file:TestHTTPSource.java
public void doTestHttps(String protocol) throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();/*from ww w . j a v a 2 s . co m*/ List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < 10; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } input.put("MsgNum", String.valueOf(i)); JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8")); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); HttpsURLConnection httpsURLConnection = null; try { TrustManager[] trustAllCerts = { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // noop } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sc = null; javax.net.ssl.SSLSocketFactory factory = null; if (System.getProperty("java.vendor").contains("IBM")) { sc = SSLContext.getInstance("SSL_TLS"); } else { sc = SSLContext.getInstance("SSL"); } HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; sc.init(null, trustAllCerts, new SecureRandom()); if (protocol != null) { factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol); } else { factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(factory); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); URL sslUrl = new URL("https://0.0.0.0:" + sslPort); httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection(); httpsURLConnection.setDoInput(true); httpsURLConnection.setDoOutput(true); httpsURLConnection.setRequestMethod("POST"); httpsURLConnection.getOutputStream().write(json.getBytes()); int statusCode = httpsURLConnection.getResponseCode(); Assert.assertEquals(200, statusCode); Transaction transaction = channel.getTransaction(); transaction.begin(); for (int i = 0; i < 10; i++) { Event e = channel.take(); Assert.assertNotNull(e); Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum")); } transaction.commit(); transaction.close(); } finally { httpsURLConnection.disconnect(); } }
From source file:org.apache.stratos.cli.RestCommandLineService.java
/** * Authenticate and login to stratos server. * * @param serverURL URL of the server * @param username username/*from www . j a va 2 s.com*/ * @param password password * @param validateLogin validate login * @return boolean * @throws Exception */ public boolean login(String serverURL, String username, String password, boolean validateLogin) throws Exception { try { // Avoid validating SSL certificate SSLContext sc = SSLContext.getInstance("SSL"); // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { 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() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; sc.init(null, trustAllCerts, new java.security.SecureRandom()); SSLContext.setDefault(sc); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception e) { throw new RuntimeException("Error while authentication process!", e); } // Initialize client try { initializeRestClient(serverURL, username, password); if (log.isDebugEnabled()) { log.debug("Initialized REST Client for user {}", username); } } catch (AxisFault e) { String message = "Error connecting to the stratos server"; printError(message, e); throw new CommandException(e); } DefaultHttpClient httpClient = new DefaultHttpClient(); try { if (validateLogin) { HttpResponse response = restClient.doGet(httpClient, restClient.getBaseURL() + ENDPOINT_INIT); if (response != null) { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200) { return true; } else { System.out.println("Invalid value is set for STRATOS_URL"); } } return false; } else { // Just return true as we don't need to validate return true; } } catch (ConnectException e) { String message = "Could not connect to stratos manager"; printError(message, e); return false; } catch (java.lang.NoSuchMethodError e) { String message = "Authentication failed!"; printError(message, e); return false; } catch (Exception e) { if (e.getCause() instanceof MalformedChallengeException) { String message = "Authentication failed. Please check your username/password"; printError(message, e); return false; } String message = "An unknown error occurred: " + e.getMessage(); printError(message, e); return false; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.marklogic.client.functionaltest.TestSSLConnection.java
@Test public void testSSLConnectionInvalidPassword() throws IOException, NoSuchAlgorithmException, KeyManagementException { System.out.println("Running testSSLConnectionInvalidPassword"); String filename = "facebook-10443244874876159931"; // create a trust manager // (note: a real application should verify certificates) TrustManager naiveTrustMgr = new X509TrustManager() { @Override//from w ww . j a v a 2s. co m public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; // create an SSL context SSLContext sslContext = SSLContext.getInstance("SSLv3"); sslContext.init(null, new TrustManager[] { naiveTrustMgr }, null); // create the client // (note: a real application should use a COMMON, STRICT, or implemented hostname verifier) DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8012, "rest-admin", "foo", Authentication.DIGEST, sslContext, SSLHostnameVerifier.ANY); String expectedException = "FailedRequestException: Local message: write failed: Unauthorized"; String exception = ""; // write doc try { writeDocumentUsingStringHandle(client, filename, "/write-text-doc/", "Text"); } catch (Exception e) { exception = e.toString(); } System.out.println("Actual exception: " + exception); boolean isExceptionThrown = exception.contains(expectedException); assertTrue("Exception is not thrown", isExceptionThrown); // release client client.release(); }
From source file:de.codesourcery.eve.apiclient.AbstractHttpAPIClient.java
private ThreadSafeClientConnManager getConnectionManager() { if (connectionManager == null) { // Create and initialize HTTP parameters final HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 30); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // setup SSL try {/* w w w .java 2 s . co m*/ SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); schemeRegistry.register(httpsScheme); } catch (Exception e) { LOG.error("getConnectionManager(): Failed to setup SSL protocol for http client", e); throw new RuntimeException(e); } // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); } return connectionManager; }
From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java
private void downloadInstaller(String downloadUrl) { String fileName = getInstallerName(downloadUrl); InputStream in;// w ww .j ava 2 s .c o m // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { // here is the place to check client certs and throw an // exception if certs are wrong. When there is nothing all certs // accepted. } public void checkServerTrusted(X509Certificate[] certs, String authType) { // here is the place to check server certs and throw an // exception if certs are wrong. When there is nothing all certs // accepted. } } }; // Install the all-trusting trust manager try { final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { // Here is the palce to check host name against to // certificate owner return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (KeyManagementException | NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { } try { URL url = new URL(downloadUrl); in = url.openStream(); FileOutputStream fos = new FileOutputStream(new File(fileName)); int length = -1; ProgressMonitorInputStream pmis; pmis = new ProgressMonitorInputStream(null, "Downloading new version of installer for NBIA Data Retriever...", in); ProgressMonitor monitor = pmis.getProgressMonitor(); monitor.setMillisToPopup(0); monitor.setMinimum(0); monitor.setMaximum((int) 200000000); // The actual size is much // smaller, // but we have no way to // know // the actual size so picked // this big number byte[] buffer = new byte[1024];// buffer for portion of data from // connection while ((length = pmis.read(buffer)) > 0) { fos.write(buffer, 0, length); } pmis.close(); fos.flush(); fos.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.craftercms.studio.impl.v1.service.cmis.CmisServiceImpl.java
private SSLContext getSSLContext() throws KeyManagementException, NoSuchAlgorithmException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }//from w w w . java 2 s .com public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); return sc; }
From source file:com.hybris.mobile.app.commerce.CommerceApplicationBase.java
public void onCreate() { super.onCreate(); mInstance = this; String urlBackend = getStringFromSharedPreferences(getString(R.string.preference_key_value_base_url), ""); String catalogStore = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_store), "");/*from w w w . java 2 s. com*/ String catalogId = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_id), ""); String catalogMainCategory = getStringFromSharedPreferences( getString(R.string.preference_key_value_catalog_main_category_id), ""); // Setting the default backend url if (StringUtils.isBlank(urlBackend)) { urlBackend = getString(R.string.url_backend); int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_url_values), urlBackend); // Update the settings setStringToSharedPreferences(getString(R.string.preference_key_value_base_url), urlBackend); setStringToSharedPreferences(getString(R.string.preference_key_key_base_url), getResources().getStringArray(R.array.backend_url_keys)[index]); } // Setting the default catalog if (StringUtils.isBlank(catalogStore)) { catalogStore = getString(R.string.url_path_catalog); setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_store), catalogStore); } if (StringUtils.isBlank(catalogId)) { catalogId = getString(R.string.url_path_catalog_id); setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_id), catalogId); } if (StringUtils.isBlank(catalogMainCategory)) { catalogMainCategory = getString(R.string.id_category_main); setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_main_category_id), catalogMainCategory); } // Updating the pre-defined catalog key String catalogKey = catalogStore + "|" + catalogId + "|" + catalogMainCategory; int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_catalog_values), catalogKey); setStringToSharedPreferences(getString(R.string.preference_key_key_catalog), getResources().getStringArray(R.array.backend_catalog_keys)[index]); // Configuration for the backend url com.hybris.mobile.lib.commerce.Configuration configuration = new com.hybris.mobile.lib.commerce.Configuration(); configuration.setBackendUrl(urlBackend); configuration.setCatalogId(catalogId); configuration.setCatalog(catalogStore); configuration.setCatalogVersionId(mInstance.getString(R.string.url_path_catalog_version_id)); configuration.setCatalogAuthority(getString(R.string.provider_authority)); configuration.setCatalogIdMainCategory(catalogMainCategory); // Bypassing SSLHelperSyncService TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManager, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException | KeyManagementException e) { Log.e(TAG, "Error with SSLHelperSyncService. Details: " + e.getLocalizedMessage()); } if (sslContext == null) { throw new IllegalStateException("Unable to get an instance of SSLContext"); } // Creating the content service helper mInstance.mContentServiceHelper = buildContentServiceHelper(configuration, sslContext.getSocketFactory(), new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); // Build the configuration for the app mConfiguration = Configuration.buildConfiguration(this); // Barcode scanner instance mScannerHelper = new ScannerHelper(new CommerceBarcodeCheckerFactory()); // Register local broadcast to Logout LocalBroadcastManager.getInstance(this).registerReceiver(new LogoutBroadcastReceiver(), new IntentFilter(getString(R.string.intent_action_logout))); // Register local broadcast to update cache on the content service helper LocalBroadcastManager.getInstance(this).registerReceiver(new UpdateCacheBroadcastReceiver(), new IntentFilter(getString(R.string.intent_action_update_cache))); // Default account for the sync adapter addCatalogSyncAdapterDefaultAccount(); // We sync in advance the main category of the catalog to create the sync adapter and accelerate the process Bundle bundle = new Bundle(); bundle.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, catalogMainCategory); bundle.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE, 0); bundle.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, mConfiguration.getDefaultPageSize()); requestCatalogSyncAdapter(bundle); }
From source file:org.jets3t.service.utils.RestUtils.java
public static DefaultHttpClient wrapClient(HttpParams params) { try {//ww w .j a v a 2 s . com SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); ClientConnectionManager ccm = new ConnManagerFactory().newInstance(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception ex) { ex.printStackTrace(); return null; } }