List of usage examples for javax.net.ssl SSLContext init
public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException
From source file:org.apache.stratos.cli.WebClientWrapper.java
public static HttpClient wrapClient(HttpClient base) { try {/*from w ww . j ava2s.c o m*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { return null; } }
From source file:com.senseidb.dataprovider.http.HttpsClientDecorator.java
public static DefaultHttpClient decorate(DefaultHttpClient base) { try {/*from www . java2 s . c om*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { logger.error(ex.getMessage(), ex); return null; } }
From source file:com.liferay.sync.engine.lan.session.LanSession.java
private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null);/*from w ww . j a v a 2s .co m*/ for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; } try { PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()); if (privateKey == null) { _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId()); continue; } X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); if (x509Certificate == null) { _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId()); continue; } keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate); keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(), new Certificate[] { x509Certificate }); } catch (Exception e) { _logger.error(e.getMessage(), e); } } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:com.aware.ui.Plugins_Manager.java
/** * Downloads and compresses image for optimized icon caching * @param image_url/* w w w .j ava 2 s .c o m*/ * @return */ public static byte[] cacheImage(String image_url, Context sContext) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = sContext.getResources().openRawResource(R.raw.aware); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); } KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework); sKeyStore.load(inStream, "awareframework".toCharArray()); inStream.close(); sKeyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(sKeyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); //Fetch image now that we recognise SSL URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection(); image_connection.setSSLSocketFactory(context.getSocketFactory()); InputStream in_stream = image_connection.getInputStream(); Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream); ByteArrayOutputStream output = new ByteArrayOutputStream(); tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output); return output.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; }
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void trustSSL() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }//from ww w. ja v a 2 s.c om public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // c'est un pb de scurit, il faudrait mettre jour les certifs racine et supprimer le all-trusting trust manager // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { System.out.println("Can not install the all-trusting trust manager"); } }
From source file:bear.plugins.java.JenkinsCache.java
public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {// w ww . j a v a 2 s.c o m Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); schemeRegistry.register(httpsScheme); schemeRegistry.register(httpScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // closes the single connection // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {/*from w w w . j av a 2 s. c o m*/ Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; // agent.get() // agent.get() SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); MechanizeAgent agent = new MechanizeAgent(); Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com"); cookie2.getHttpCookie().setPath("/"); cookie2.getHttpCookie().setSecure(false); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:org.orcid.examples.jopmts.impl.SSLConfig.java
public static void trustSelfSignedSSL() { try {/* www. j av a2 s. com*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLContext.setDefault(ctx); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java
private static DefaultHttpClient wrapClient(HttpClient base) { try {//from w w w . j a v a 2 s. c o m SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:com.vmware.admiral.test.integration.BaseIntegrationSupportIT.java
protected static SSLSocketFactory getUnsecuredSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { UnsecuredX509TrustManager.getInstance() }, null); return context.getSocketFactory(); }