List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final String[] supportedProtocols, final String[] supportedCipherSuites, final X509HostnameVerifier hostnameVerifier)
From source file:com.helger.pd.client.jdk6.PDClient.java
@Nonnull protected HttpClientBuilder createClientBuilder() { SSLConnectionSocketFactory aSSLSocketFactory = null; try {//from ww w .jav a 2s.c o m // Set SSL context final KeyStore aKeyStore = KeyStoreHelper.loadKeyStore(PDClientConfiguration.getKeyStorePath(), PDClientConfiguration.getKeyStorePassword()); final SSLContext aSSLContext = SSLContexts.custom().loadKeyMaterial(aKeyStore, PDClientConfiguration.getKeyStoreKeyPassword(), new PrivateKeyStrategy() { public String chooseAlias(final Map<String, PrivateKeyDetails> aAliases, final Socket aSocket) { final String sAlias = PDClientConfiguration.getKeyStoreKeyAlias(); return aAliases.containsKey(sAlias) ? sAlias : null; } }).build(); // Allow TLSv1 protocol only aSSLSocketFactory = new SSLConnectionSocketFactory(aSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (final Throwable t) { s_aLogger.error("Failed to initialize keystore for service connection! Can only use http now!", t); } try { final RegistryBuilder<ConnectionSocketFactory> aRB = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()); if (aSSLSocketFactory != null) aRB.register("https", aSSLSocketFactory); final Registry<ConnectionSocketFactory> sfr = aRB.build(); final PoolingHttpClientConnectionManager aConnMgr = new PoolingHttpClientConnectionManager(sfr); aConnMgr.setDefaultMaxPerRoute(100); aConnMgr.setMaxTotal(200); aConnMgr.setValidateAfterInactivity(1000); final ConnectionConfig aConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build(); aConnMgr.setDefaultConnectionConfig(aConnectionConfig); return HttpClientBuilder.create().setConnectionManager(aConnMgr); } catch (final Exception ex) { throw new InitializationException("Failed to init HTTP client", ex); } }
From source file:io.cloudslang.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java
public SSLConnectionSocketFactory build() { if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) { throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'"); }/*www . j a v a 2s . c o m*/ boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr); SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (!trustAllRoots) { boolean useClientCert = !StringUtils.isEmpty(keystore); //validate SSL certificates sent by the server boolean useTrustCert = !StringUtils.isEmpty(trustKeystore); String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts"; boolean storeExists = new File(javaKeystore).exists(); if (!useClientCert && storeExists) { keystore = "file:" + javaKeystore; keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword; useClientCert = true; } else if (useClientCert && !keystore.startsWith("http")) { keystore = "file:" + keystore; } if (!useTrustCert && storeExists) { trustKeystore = "file:" + javaKeystore; trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword; useTrustCert = true; } else if (useTrustCert && !trustKeystore.startsWith("http")) { trustKeystore = "file:" + trustKeystore; } createTrustKeystore(sslContextBuilder, useTrustCert); //todo client key authentication should not depend on 'trustAllRoots' createKeystore(sslContextBuilder, useClientCert); } else { try { //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots, e); } } sslContextBuilder.useSSL(); sslContextBuilder.useTLS(); SSLConnectionSocketFactory sslsf; try { String x509HostnameVerifierStr = x509HostnameVerifierInputValue.toLowerCase(); X509HostnameVerifier x509HostnameVerifier; switch (x509HostnameVerifierStr) { case "strict": x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; break; case "browser_compatible": x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; break; case "allow_all": x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; break; default: throw new IllegalArgumentException("Invalid value '" + x509HostnameVerifierInputValue + "' for input 'x509HostnameVerifier'. Valid values: 'strict','browser_compatible','allow_all'."); } // Allow SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols only. Client-server communication starts with TLSv1.2 and fallbacks to SSLv3 if needed. sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), SUPPORTED_PROTOCOLS, null, x509HostnameVerifier); } catch (Exception e) { if (e instanceof IllegalArgumentException) { throw new IllegalArgumentException(e.getMessage()); } throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e); } return sslsf; }
From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImplIT.java
private void setSSL(HttpClientBuilder builder) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(this.getClass().getClassLoader().getResource("testkeystore"), "password".toCharArray(), new TrustSelfSignedStrategy()) .build();/*from w ww . j av a 2s . c o m*/ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); }
From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java
protected final CloseableHttpClient getHTTPClient() throws Exception { final HttpClientBuilder hcb = HttpClients.custom(); if (enableHTTPClientSSL) { log.debug("Configure HTTP client with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHTTPServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }//from w ww . ja v a2 s .c o m if (sendHTTPClientCertificate) { sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); String[] protocols = null; if (enableHTTPClientSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); return hcb.build(); }
From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java
public void testThatHttpUsingSSLv3IsRejected() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init((KeyStore) null); sslContext.init(null, factory.getTrustManagers(), new SecureRandom()); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv3" }, null, NoopHostnameVerifier.INSTANCE); try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) { CloseableHttpResponse result = SocketAccess .doPrivileged(() -> client.execute(new HttpGet(getNodeUrl()))); fail("Expected a connection error due to SSLv3 not being supported by default"); } catch (Exception e) { assertThat(e, is(instanceOf(SSLHandshakeException.class))); }//from w w w .j ava2 s .c o m }
From source file:org.votingsystem.util.HttpHelper.java
private HttpHelper() { try {//from ww w .j a v a2 s.co m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLContext sslcontext = null; SSLConnectionSocketFactory sslsf = null; if (ContextVS.getInstance().getVotingSystemSSLCerts() != null) { log.info("loading SSLContext with app certificates"); X509Certificate sslServerCert = ContextVS.getInstance().getVotingSystemSSLCerts().iterator().next(); trustStore.setCertificateEntry(sslServerCert.getSubjectDN().toString(), sslServerCert); sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build(); X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) new AllowAllHostnameVerifier(); sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, hostnameVerifier); } else { sslcontext = SSLContexts.createSystemDefault(); sslsf = new SSLConnectionSocketFactory(sslcontext); log.info("loading default SSLContext"); } // Create a registry of custom connection socket factories for supported protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslsf).build(); //Create socket configuration //SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); //Configure the connection manager to use socket configuration either by default or for a specific host. //connManager.setDefaultSocketConfig(socketConfig); connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver); connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(100); connEvictor = new IdleConnectionEvictor(connManager); connEvictor.start(); HttpRoute httpRouteVS = new HttpRoute(new HttpHost("www.sistemavotacion.org", 80)); connManager.setMaxPerRoute(httpRouteVS, 200); /* timeouts with large simulations -> RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIME_OUT) .setConnectionRequestTimeout(REQUEST_TIME_OUT).setSocketTimeout(REQUEST_TIME_OUT).build(); httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig( requestConfig).build();*/ httpClient = HttpClients.custom().setConnectionManager(connManager).build(); } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); } }
From source file:cn.mrdear.pay.util.WebUtils.java
/** * ?/*from w ww . j a v a 2s . c o m*/ * @param certPath ? * @param passwd ?? * @param uri ? * @param entity xml * @return */ public static String post(String certPath, String passwd, String uri, InputStreamEntity entity) throws Exception { String result = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File(certPath)); try { keyStore.load(instream, passwd.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httpPost = new HttpPost(uri); entity.setContentEncoding("UTF-8"); httpPost.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPost); result = consumeResponse(httpResponse); } finally { httpclient.close(); } return result; }
From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java
private SSLConnectionSocketFactory configureSsl() throws OfficeException { if (sslConfig == null || !sslConfig.isEnabled()) { return null; }//from w w w.jav a 2s . co m try { final SSLContextBuilder sslBuilder = SSLContexts.custom(); sslBuilder.setProtocol(sslConfig.getProtocol()); configureKeyMaterial(sslBuilder); configureTrustMaterial(sslBuilder); final SSLContext sslcontext = sslBuilder.build(); return new SSLConnectionSocketFactory(sslcontext, sslConfig.getEnabledProtocols(), sslConfig.getCiphers(), sslConfig.isVerifyHostname() ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE); } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException | NoSuchProviderException ex) { throw new OfficeException("Unable to create SSL context.", ex); } }
From source file:org.wisdom.framework.vertx.ServerTest.java
/** * This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication. *//*from w w w.ja v a2 s . c o m*/ @Test public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException { FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", false).put("authentication", false).build()); FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", false).build()); FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", true).build()); // Server HTTPS File root = new File(""); final File serverKeyStore = new File( root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks"); assertThat(serverKeyStore).isFile(); when(application.get("https.keyStore")).thenReturn(serverKeyStore.getAbsolutePath()); when(application.get("https.trustStore")) .thenReturn(new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks") .getAbsolutePath()); when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getConfiguration("vertx.servers")) .thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2, "s3", s3))); Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { return ok("Alright"); } }; Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index"); when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route); wisdom.start(); waitForStart(wisdom); waitForHttpsStart(wisdom); assertThat(wisdom.servers).hasSize(3); // Check rendering for (Server server : wisdom.servers) { String r; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks"); trustStore.load(instream, "wisdom".toCharArray()); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .loadKeyMaterial(trustStore, "wisdom".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1", "SSLv3" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); if (server.ssl()) { HttpGet httpget = new HttpGet("https://localhost:" + server.port()); final CloseableHttpResponse response = httpclient.execute(httpget); r = EntityUtils.toString(response.getEntity()); } else { r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port()).execute() .returnContent().asString(); } assertThat(r).isEqualToIgnoringCase("Alright"); } }