List of usage examples for org.apache.http.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
@Override protected void configureClient() { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try {//from w ww . j av a2 s . co m String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }
From source file:org.thingsboard.server.msa.AbstractContainerTest.java
private static HttpComponentsClientHttpRequestFactory getRequestFactoryForSelfSignedCert() throws Exception { SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslSelfSigned = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override//from ww w. j av a 2s. c om public void verify(String host, SSLSocket ssl) { } @Override public void verify(String host, X509Certificate cert) { } @Override public void verify(String host, String[] cns, String[] subjectAlts) { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSelfSigned).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); return new HttpComponentsClientHttpRequestFactory(httpClient); }
From source file:org.apache.hadoop.gateway.shell.Hadoop.java
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException { // SSL/* w w w . j ava 2 s.c om*/ HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = null; if (clientContext.connection().secure()) { hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { trustStrategy = TrustSelfSignedStrategy.INSTANCE; System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************"); } KeyStore trustStore = getTrustStore(); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); // Pool PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(clientContext.pool().maxTotal()); connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute()); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize(clientContext.connection().bufferSize()).build(); connectionManager.setDefaultConnectionConfig(connectionConfig); SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()) .setSoLinger(clientContext.socket().linger()) .setSoReuseAddress(clientContext.socket().reuseAddress()) .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()) .build(); connectionManager.setDefaultSocketConfig(socketConfig); // Auth URI uri = URI.create(clientContext.url()); host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credentialsProvider = null; if (clientContext.username() != null && clientContext.password() != null) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password())); AuthCache authCache = new BasicAuthCache(); BasicScheme authScheme = new BasicScheme(); authCache.put(host, authScheme); context = new BasicHttpContext(); context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache); } return HttpClients.custom().setConnectionManager(connectionManager) .setDefaultCredentialsProvider(credentialsProvider).build(); }
From source file:com.helger.pd.client.jdk6.PDClient.java
@Nonnull protected HttpClientBuilder createClientBuilder() { SSLConnectionSocketFactory aSSLSocketFactory = null; try {/*from ww w . j ava 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:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
/** * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context. * @return a HTTP client that will trust own CA and self-signed certificates. * @throws Exception if an error occurs. */// w ww .j av a 2 s . c o m private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password, final String url) { CloseableHttpClient httpClient = null; try { final File trustStoreFile = new File(trustStoreDir, "trusted.keystore"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // create a new, empty trust store if (!trustStoreFile.exists()) { trustStoreDir.mkdirs(); trustStoreFile.createNewFile(); trustStore.load(null, password); } // import certificate to trust store importCertificate(url, trustStore); // save trust store to disk try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) { trustStore.store(outstream, password); } // trust own CA and all self-signed certificates final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // allow trusted protocols only final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, new DefaultHostnameVerifier()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception e) { LOGGER.error("Failed to create HTTP client", e); } return httpClient; }
From source file:com.liferay.sync.engine.session.Session.java
public static void setTrustManagers(TrustManager[] trustManagers) throws Exception { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); SSLContext sslContext = sslContextBuilder.build(); sslContext.init(null, trustManagers, new SecureRandom()); _defaultSSLSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); }
From source file:org.ulyssis.ipp.publisher.HttpServerPublisher.java
private SSLContext sslContext() { try {// w w w . j a v a 2 s. c om KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType()); cks.load(new FileInputStream(options.getKeystore().get().toFile()), options.getKeystorePass().toCharArray()); SSLContextBuilder builder = SSLContexts.custom(); if (options.getTruststore().isPresent()) { KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType()); tks.load(new FileInputStream(options.getTruststore().get().toFile()), options.getTruststorePass().toCharArray()); builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy()); } return builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()).build(); } catch (Exception e) { // TODO: DO SOMETHING WITH THE EXCEPTION! LOG.error("Exception", e); } return null; }
From source file:com.vmware.photon.controller.nsxclient.RestClient.java
/** * Creates a HTTP client.//from w w w . ja v a2 s . com */ private CloseableHttpAsyncClient getHttpClient() { try { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build(); CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClientBuilder.create() .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext) .build(); httpAsyncClient.start(); return httpAsyncClient; } catch (Throwable e) { throw new RuntimeException(e); } }
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();// w w w . j a v a 2 s . c om SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*www. j a v a 2 s.co m*/ }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }