List of usage examples for javax.net.ssl SSLContext getInstance
public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException
From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java
/** Open a connexion to each Stack */ public boolean open() throws Exception { if (this.secure) { StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS, StackFactory.PROTOCOL_HTTP); } else {/*from ww w .j a v a 2 s .co m*/ StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP, StackFactory.PROTOCOL_HTTP); } this.startTimestamp = System.currentTimeMillis(); if (null != this.socketServerHttp) { ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp); } else { String host = this.getRemoteHost(); int port = this.getRemotePort(); DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection(); Socket socket; if (this.secure) { // Create a trust manager that does not validate certificate chains like the default TrustManager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, null); socket = sslContext.getSocketFactory().createSocket(); // read all properties for the TCP socket Config.getConfigForTCPSocket(socket, true); } else { // // Create a TCP non secure socket // socket = new Socket(); // read all properties for the TCP socket Config.getConfigForTCPSocket(socket, false); } // // Bind the socket to the local address // String localHost = this.getLocalHost(); int localPort = initialLocalport; if (null != localHost) { socket.bind(new InetSocketAddress(localHost, localPort)); } else { socket.bind(new InetSocketAddress(localPort)); } socket.setReceiveBufferSize(65536); socket.connect(new InetSocketAddress(host, port)); this.setLocalPort(socket.getLocalPort()); HttpParams params = new BasicHttpParams(); defaultHttpClientConnection.bind(socket, params); this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this); ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp); } return true; }
From source file:me.vertretungsplan.parser.BaseParser.java
BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { this.scheduleData = scheduleData; this.cookieProvider = cookieProvider; this.cookieStore = new BasicCookieStore(); this.colorProvider = new ColorProvider(scheduleData); this.encodingDetector = new UniversalDetector(null); try {//from ww w. ja v a 2 s .c o m KeyStore ks = loadKeyStore(); MultiTrustManager multiTrustManager = new MultiTrustManager(); multiTrustManager.addTrustManager(getDefaultTrustManager()); multiTrustManager.addTrustManager(trustManagerFromKeystore(ks)); TrustManager[] trustManagers = new TrustManager[] { multiTrustManager }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); final HostnameVerifier hostnameVerifier; if (scheduleData.getData() != null && scheduleData.getData().has(PARAM_SSL_HOSTNAME)) { hostnameVerifier = new CustomHostnameVerifier(scheduleData.getData().getString(PARAM_SSL_HOSTNAME)); } else { hostnameVerifier = new DefaultHostnameVerifier(); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new LaxRedirectStrategy()) .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()) .build(); this.executor = Executor.newInstance(httpclient).use(cookieStore); } catch (GeneralSecurityException | JSONException | IOException e) { throw new RuntimeException(e); } }
From source file:com.oneis.common.utils.SSLCertificates.java
public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet) throws Exception { // For some indiciation of what's going on early in the boot process if (!quiet) { System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory); }//w w w. j a va 2s. c o m // Get filenames String keyPathname = keysDirectory + "/" + certsName + ".key"; String certPathname = keysDirectory + "/" + certsName + ".crt"; final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate"; String clientCAPathname = null; if (clientCAName != null) { clientCAPathname = keysDirectory + "/" + clientCAName + ".crt"; } if (!new File(keyPathname).exists()) { System.out.println("Doesn't exist: " + keyPathname); return null; } if (!new File(certPathname).exists()) { System.out.println("Doesn't exist: " + certPathname); return null; } if (clientCAPathname != null) { if (!new File(clientCAPathname).exists()) { System.out.println("Doesn't exist: " + clientCAPathname); return null; } } char[] nullPassword = {}; PrivateKey privateKey = readPEMPrivateKey(keyPathname); CertificateFactory cf = CertificateFactory.getInstance("X.509"); // Server certificate ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4); java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname)); certList.add(cert); // Optional intermediate certificates int intermediateCounter = 1; while (true) { String intermediateCertPathname = intermediateCertPathnameBase; if (intermediateCounter != 1) { intermediateCertPathname += "-" + intermediateCounter; } intermediateCounter++; intermediateCertPathname += ".crt"; if (new File(intermediateCertPathname).exists()) { certList.add(cf.generateCertificate(readPEM(intermediateCertPathname))); } else { // End of cert list break; } } // Optional client CA certificate java.security.cert.Certificate clientCACert = null; if (clientCAPathname != null) { clientCACert = cf.generateCertificate(readPEM(clientCAPathname)); } if (clientCAName != null && clientCACert == null) { throw new RuntimeException("Logic error, failed to load client CA cert when required"); } KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, nullPassword); ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(), certList.toArray(new java.security.cert.Certificate[certList.size()])); if (clientCACert != null) { KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert); ks.setEntry("CLIENTCA", tce, null); } // Generate some random Java API stuff, just for entertainment KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, nullPassword); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); if (!quiet) { System.out.println(" - server cert chain length " + certList.size() + (clientCACert != null ? ", requires client cert" : ", public server")); } return sslContext; }
From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java
private synchronized CloseableHttpClient getHttpclient(HistoDbConfig config) { if (httpClient == null) { try {//ww w . j av a 2s. c o m ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf).register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); cm.setDefaultMaxPerRoute(10); cm.setMaxTotal(20); HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(new HttpHost(config.getConnectionParameters().getHost(), config.getConnectionParameters().getPort())), new UsernamePasswordCredentials(config.getConnectionParameters().getUserName(), config.getConnectionParameters().getPassword())); if (config.getProxyParameters() != null) { HttpHost proxy = new HttpHost(config.getProxyParameters().getHost(), config.getProxyParameters().getPort()); credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials( config.getProxyParameters().getUserName(), config.getProxyParameters().getPassword())); httpClientBuilder.setProxy(proxy); } httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build(); } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } return httpClient; }
From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java
private HttpURLConnection getConnection(String urlString) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException { if (urlString.startsWith("https://")) { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString)); connection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; }//from w w w . ja v a 2s . com }); return connection; } else if (urlString.contains("@")) { URL passedURL = new URL(urlString); String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@")); String userName = creds.substring(0, creds.indexOf(":")); String passWord = creds.substring(creds.indexOf(":") + 1, creds.length()); String userPassword = userName + ":" + passWord; // TODO cambiar implementacin de Base64 String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); // TODO soporta proxy? HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); return connection; } else { return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString)); } }
From source file:org.ckan.Connection.java
/** * Makes a POST request/* w w w . j av a 2 s . com*/ * * Submits a POST HTTP request to the CKAN instance configured within * the constructor, returning the entire contents of the response. * * @param path The URL path to make the POST request to * @param data The data to be posted to the URL * @returns The String contents of the response * @throws A CKANException if the request fails */ protected String post(String path, String data) throws CKANException { URL url = null; try { url = new URL(this.m_host + ":" + this.m_port + path); } catch (MalformedURLException mue) { System.err.println(mue); return null; } String body = ""; BasicClientConnectionManager bccm = null; ClientConnectionManager cm = null; try { /***********************************************************************/ SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything 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); //bccm = new BasicClientConnectionManager(schemeRegistry); // apache HttpClient version >4.2 should use BasicClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); /***********************************************************************/ } catch (KeyManagementException kme) { System.out.println("Con ex: " + kme.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println("Con ex: " + nsae.getMessage()); } //HttpClient httpclient = new DefaultHttpClient(cm); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost postRequest = new HttpPost(url.toString()); postRequest.setHeader("X-CKAN-API-Key", this._apikey); StringEntity input = new StringEntity(data); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpclient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String line = ""; while ((line = br.readLine()) != null) { body += line; } } catch (IOException ioe) { System.out.println(ioe); } finally { httpclient.getConnectionManager().shutdown(); } return body; }
From source file:org.apache.juneau.rest.test.TestMicroservice.java
static SSLConnectionSocketFactory getSSLSocketFactory() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager tm = new SimpleX509TrustManager(true); sslContext.init(null, new TrustManager[] { tm }, new SecureRandom()); return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:com.cerema.cloud2.lib.common.network.NetworkUtils.java
public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext;/*from w w w . ja va 2s . c om*/ try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0"); sslContext = SSLContext.getInstance("TLSv1"); // should be available in any device; see reference of supported protocols in // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html } sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; }
From source file:com.nextdoor.bender.ipc.http.AbstractHttpTransportFactory.java
/** * There isn't an easy way in java to trust non-self signed certs. Just allow all until java * KeyStore functionality is added to Bender. * * @return a context that trusts all SSL certs *///w w w . ja va2 s . co m private SSLContext getSSLContext() { /* * Create SSLContext and TrustManager that will trust all SSL certs. * * Copy pasta from http://stackoverflow.com/a/4837230 */ TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx; try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { throw new TransportFactoryInitException("JVM does not have proper libraries for TSL"); } try { ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom()); } catch (KeyManagementException e) { throw new TransportFactoryInitException("Unable to init SSLContext with TrustManager", e); } return ctx; }
From source file:com.owncloud.android.lib.common.network.NetworkUtils.java
public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext;/* ww w . ja v a2 s .c o m*/ try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0"); sslContext = SSLContext.getInstance("TLSv1"); // should be available in any device; see reference of supported protocols in // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html } sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; }