private static HttpClient createAllTrustingClient() throws RestClientException { HttpClient httpclient = null; try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial((TrustStrategy) (X509Certificate[] chain, String authType) -> true); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); httpclient = HttpClients .custom() .setSSLSocketFactory(sslsf) .setMaxConnTotal(1000) .setMaxConnPerRoute(1000) .build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new RestClientException("Cannot create all SSL certificates trusting client", e); } return httpclient; }
/** * Creates the security rest template. * * @throws KeyManagementException the key management exception * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception */ private void createSecurityRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException{ TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); HttpClient httpClient = HttpClientBuilder.create() .disableCookieManagement() .useSystemProperties() .setSSLSocketFactory(csf) .build(); requestFactory.setHttpClient(httpClient); this.restTemplate = new RestTemplate(requestFactory); }
/** * 获取LayeredConnectionSocketFactory 使用ssl单向认证 * * @date 2015年7月17日 * @return */ private LayeredConnectionSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
/** * custom http client for server with SSL errors * * @return */ public final CloseableHttpClient getCustomClient() { try { HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build(); builder.setSSLContext(sslContext); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); builder.setConnectionManager(connMgr); return builder.build(); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return getSystemClient(); }
@SuppressWarnings("deprecation") static CloseableHttpClient buildClient(boolean ignoreSSL) throws Exception { SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted( final X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy... return true; } }); if (ignoreSSL) { return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { return HttpClients.createDefault(); } }
private CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (cert != null) { for (X509Certificate chainCert : chain) { if (chainCert.equals(cert)) { return true; } } return false; } return true; } }).build(); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(factory).build(); } catch (GeneralSecurityException e) { logger.error(String.format("SSL connection create Fail : %s", e.getMessage())); } return HttpClients.createDefault(); }
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() { try { SSLContext sslcontext = SSLContexts.custom() //忽略掉对服务器端证书的校验 .loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); return new SSLConnectionSocketFactory( sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { this.log.error(e.getMessage(), e); } return null; }
private CloseableHttpClient createHttpClientWithDisabledSSLCheck(){ SSLContext sslcontext = null; try { sslcontext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy(){ @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }) .build(); } catch (Exception e) { throw new RuntimeException("SSL Context can not be created.", e); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext); return HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); }
private SSLSocketFactory createSSLSocketFactory(boolean useKeyStoreToConnect, String keyStorePath, String keyStorePassword) throws Exception { //Only load KeyStore when it's needed to connect to IP, SSLContext is fine with KeyStore being null otherwise. KeyStore trustStore = null; if (useKeyStoreToConnect) { trustStore = KeyStoreLoader.loadKeyStore(keyStorePath, keyStorePassword); } SSLContext sslContext = SSLContexts.custom() .useSSL() .loadTrustMaterial(trustStore, new TrustStrategy() { //Always trust @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }) .loadKeyMaterial(trustStore, keyStorePassword.toCharArray()) .setSecureRandom(new java.security.SecureRandom()) .build(); return sslContext.getSocketFactory(); }
private CloseableHttpClient getHttpsClient() { try { RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build(); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true ); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE ); return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory ) .build(); } catch ( Exception e ) { LOGGER.error( e.getMessage() ); } return HttpClients.createDefault(); }
/** * Creates {@link HttpClient} that trusts any SSL certificate * * @return prepared HTTP client */ protected HttpClient getSSLAcceptingClient() { final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true; try { final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build(); sslContext.init(null, getTrustManager(), new SecureRandom()); final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) { ConsoleUtils.printError(error.getMessage()); throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error); } }
@Test @RunAsClient public void hello() throws IOException, GeneralSecurityException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true) .build(); try (CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build()) { String response = Executor.newInstance(httpClient) .execute(Request.Get("https://localhost:8443/")) .returnContent().asString(); assertThat(response).contains("Hello on port 8443, secure: true"); } }
private HttpClient getHttpClient() { CloseableHttpClient httpclient = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { _logger.error("Failed to create HTTPClient: {}", e); } return httpclient; }
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException { SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(true).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultSocketConfig(socketConfig); httpClientBuilder.disableAuthCaching(); httpClientBuilder.disableAutomaticRetries(); if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) { log.debug("Disabling all SSL certificate verification."); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); httpClientBuilder.setSSLContext(sslContextBuilder.build()); } return httpClientBuilder.build(); }
private SSLConnectionSocketFactory getSSLSocketFactory() { KeyStore trustStore; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy); sslContextBuilder.useTLS(); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); return sslSocketFactory; } catch (GeneralSecurityException | IOException e) { System.err.println("SSL Error : " + e.getMessage()); } return null; }
public void test1() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException{ // ## SHOULD FIRE OVER-PERMISSIVE HOSTNAME VERIFIER CloseableHttpClient httpClient = HttpClients.custom(). setHostnameVerifier(new AllowAllHostnameVerifier()). setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // ## SHOULD FIRE OVER-PERMISSIVE TRUST MANAGER @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { return true; } }).build()).build(); HttpGet httpget = new HttpGet("https://www.google.com/"); CloseableHttpResponse response = httpClient.execute(httpget); try { System.out.println(response.toString()); } finally { response.close(); } }
@Override protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException { final SSLContext sslContext; try { sslContext = SSLContextBuilder.create() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true) .build(); } catch (GeneralSecurityException e) { throw new TTransportException("failed to initialize an SSL context", e); } final THttpClient client = new THttpClient( uri, HttpClientBuilder.create() .setSSLContext(sslContext) .build()); client.setCustomHeaders( headers.names().stream() .collect(toImmutableMap(AsciiString::toString, name -> String.join(", ", headers.getAll(name))))); return client; }
public KylinClient(KylinConnection conn) { this.conn = conn; this.connProps = conn.getConnectionProperties(); this.httpClient = new DefaultHttpClient(); this.jsonMapper = new ObjectMapper(); // trust all certificates if (isSSL()) { try { SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy... return true; } }); httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, sslsf)); } catch (Exception e) { throw new RuntimeException("Initialize HTTPS client failed", e); } } }
private CloseableHttpClient createSslHttpClient() throws Exception { final SSLContextBuilder wsBuilder = new SSLContextBuilder(); wsBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(), new AllowAllHostnameVerifier()); //This winds up using a PoolingHttpClientConnectionManager so need to pass the //RegistryBuilder final Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create().register("https", sslsf) .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); return HttpClients .custom() .setConnectionManager(cm) .build(); }
private static CloseableHttpClient createInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { final SSLContext sslContext = new SSLContextBuilder() .useProtocol(INSECURE_SSL_PROTOCOL) .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry); return HttpClients.custom() .setConnectionManager(connectionManager) .setSSLSocketFactory( sslsf).build(); }
public ExtHttpClientStack() throws VolleyError { try { SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }).build(); client = HttpClients.custom() //.setUserAgent(USER_AGENT) .setRedirectStrategy(new LaxRedirectStrategy()) .setSslcontext(sslcontext) .build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new VolleyError("Cannot create HttpClient"); } }
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final TrustStrategy acceptTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] certificate, final String authType) { return true; } }; final SchemeRegistry registry = new SchemeRegistry(); try { final SSLSocketFactory ssf = new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf)); } catch (Exception e) { throw new ODataRuntimeException(e); } final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry)); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); return httpClient; }
public HttpClient getHttpsClientTrustAll() { try { SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){ @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); PlainSocketFactory psf = PlainSocketFactory.getSocketFactory(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, psf)); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); return new DefaultHttpClient(ccm); } catch (Exception ex) { log.error("Failed to create TrustAll https client", ex); return new DefaultHttpClient(); } }
/** * Ignores certificate issues for SSL connections. Cert does not have to be from a trusted authority * and the hostname does not need to be verified. * This is primarily for dev situations that make use of localhost, build, and test servers. * * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException * */ public void ignoreSSLIssues() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException{ TrustStrategy trustStrat = new TrustStrategy(){ public boolean isTrusted(X509Certificate[] chain, String authtype) throws CertificateException { return true; } }; SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStrat,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpClient.getConnectionManager().getSchemeRegistry().register( new Scheme("https",443,sslSocketFactory ) ); }
public DefaultHttpClient BuildHttpClient() throws UnknownHostException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(registry); //ClientConnectionManager ccm=new SingleClientConnManager(registry); DefaultHttpClient httpclient = new DefaultHttpClient(ccm); ccm.setMaxTotal(999); ccm.setDefaultMaxPerRoute(10); return httpclient; }
private String getUpdateJson() { try { // battle-royale.jutge.org has an untrusted cert final TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] certificate, final String authType) throws CertificateException { return true; } }; final SSLSocketFactory socketFactory = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, socketFactory)); final ClientConnectionManager connectionManager = new PoolingClientConnectionManager(registry); // Get data final HttpClient httpClient = new DefaultHttpClient(connectionManager); final HttpGet get = new HttpGet(UPDATE_URL); final HttpResponse response = httpClient.execute(get); final HttpEntity entity = response.getEntity(); final String responseBody = EntityUtils.toString(entity); return responseBody; } catch(Exception exception) { this.logger.error(exception.getMessage()); } return null; }
protected HttpClient createClient() throws Exception { DefaultHttpClient result = new DefaultHttpClient(); SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); Scheme httpsScheme2 = new Scheme("https", 443, sslsf); sr.register(httpsScheme2); return result; }
public void createSession(String alias, String url, Map<String, String> headers, Authentication auth, String verify, Boolean debug, String loggerClass, String password, boolean verifyHost, boolean selfSigned, Proxy proxy) { HostnameVerifier defaultHostnameVerifier = verifyHost ? null : NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = selfSigned ? new TrustSelfSignedStrategy() : null; if (!loggerClass.isEmpty()) { System.setProperty("org.apache.commons.logging.Log", loggerClass); System.setProperty("org.apache.commons.logging.robotlogger.log.org.apache.http", debug ? "DEBUG" : "INFO"); } HttpHost target; try { target = URIUtils.extractHost(new URI(url)); } catch (URISyntaxException e) { throw new RuntimeException("Parsing of URL failed. Error message: " + e.getMessage()); } Session session = new Session(); session.setProxy(proxy); session.setContext(this.createContext(auth, target)); session.setClient(this.createHttpClient(auth, verify, target, false, password, null, null, proxy)); session.setUrl(url); session.setHeaders(headers); session.setHttpHost(target); session.setVerify(verify); session.setAuthentication(auth); session.setPassword(password); session.setHostnameVerifier(defaultHostnameVerifier); session.setTrustStrategy(trustStrategy); sessions.put(alias, session); }
private HttpClient createHttpClient(Authentication auth, String verify, HttpHost target, Boolean postRedirects, String password, TrustStrategy keystoreTrustStrategy, HostnameVerifier keystoreHostnameVerifier, Proxy proxy) { Certificate certificate = new Certificate(); Auth authHelper = new Auth(); HttpClientBuilder httpClientBuilder = WinHttpClients.custom(); Builder requestConfig = RequestConfig.custom(); requestConfig.setCookieSpec(CookieSpecs.DEFAULT); logger.debug("Verify value: " + verify); logger.debug((new File(verify).getAbsolutePath())); if (new File(verify).exists()) { logger.debug("Loading custom keystore"); httpClientBuilder.setSSLSocketFactory( certificate.allowAllCertificates(certificate.createCustomKeyStore(verify.toString(), password), password, keystoreTrustStrategy, keystoreHostnameVerifier)); } else if (!Boolean.parseBoolean(verify.toString())) { logger.debug("Allowing all certificates"); httpClientBuilder.setSSLSocketFactory(certificate.allowAllCertificates(null)); } if (auth.isAuthenticable()) { httpClientBuilder.setDefaultCredentialsProvider(authHelper.getCredentialsProvider(auth, target)); } if (proxy != null && proxy.isInUse()) { logger.debug("Enabling proxy"); if (proxy.isAuthenticable()) { logger.debug("Setting proxy credentials"); httpClientBuilder.setDefaultCredentialsProvider( authHelper.getCredentialsProvider(proxy.getAuth(), proxy.getHttpHost())); } requestConfig.setProxy(proxy.getHttpHost()); } if (postRedirects) { httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy()); } httpClientBuilder.setDefaultRequestConfig(requestConfig.build()); return httpClientBuilder.build(); }
public static CloseableHttpAsyncClient createSSLClient(HttpHost proxy) { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }; try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); HttpAsyncClientBuilder client = HttpAsyncClients.custom() .setDefaultCookieStore(new BasicCookieStore()) .setSSLContext(sslContext) .setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); if (proxy !=null) { client.setProxy(proxy); } return client.build(); } catch (Exception e) { System.out.println("Could not create SSLContext"); return null; } }
@Override protected Registry<ConnectionSocketFactory> getRegistry() { HostnameVerifier verifier = new HostnameVerifier() { @Override public boolean verify(String hostName, SSLSession session) { return true; } }; SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { e.printStackTrace(); } if (sslContext == null) { throw new RuntimeException("SSL Context not created"); } SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext, new String[]{"TLSv1.2"}, null, verifier); return RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory) .build(); }
private static SSLContext createAcceptsAllCertsSSLContext() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { return (new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }).build()); }
private static HttpClient createHttpClientAcceptsUntrustedCertificates() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClientBuilder b = HttpClientBuilder.create(); // setup a Trust Strategy that allows all certificates. // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSslcontext(sslContext); // don't check Hostnames, either. // -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // here's the special part: // -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; // -- and create a Registry, to register it. // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // now, we create connection-manager using our Registry. // -- allows multi-threaded use PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); b.setConnectionManager(connMgr); // finally, build the HttpClient; // -- done! return b.build(); }
private CloseableHttpClient getClient(String url, String ua, long timeout) { if (ctx == null) { try { if (url.toLowerCase().startsWith("https")) { ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub return true; } }).build(); } } catch (Exception e) { log.error(e.getMessage(), e); // e.printStackTrace(); } } int t = (int) timeout; RequestConfig config = RequestConfig.custom().setConnectTimeout(t).setSocketTimeout(t) .setConnectionRequestTimeout(t).setCookieSpec("easy").build(); HttpClientBuilder builder = HttpClients.custom().setSSLContext(ctx).setDefaultRequestConfig(config) .setUserAgent(ua); if (!X.isEmpty(proxy)) { String[] ss = X.split(proxy, ":"); if (ss != null && ss.length > 1) { return builder.setProxy(new HttpHost(ss[0], X.toInt(ss[1]))).build(); } } return builder.build(); }
private HttpClient switchOffSSLVerification(HttpClient httpClient) throws GeneralSecurityException { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; SSLSocketFactory socketFactory = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", SSL_PORT, socketFactory)); return httpClient; }
private void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { if (client == null) { client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom() .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true) .build() ) ).build(); } }
private void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { if (client == null) { //TODO: properly add a correct certification authority client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom() .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true) .build() ) ).build(); } }
private SSLContext trustAllSslContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { return new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); }
public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception { // setup a Trust Strategy that allows all certificates. // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { return true; } }).build(); builder.setSslcontext(sslContext); // don't check Hostnames, either. // -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // here's the special part: // -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; // -- and create a Registry, to register it. // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // now, we create connection-manager using our Registry. // -- allows multi-threaded use PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); builder.setConnectionManager(connMgr); // finally, build the HttpClient; // -- done! return this; }
public RiscossRESTClient(String base_addr) { this.addr = base_addr; RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create(); connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE); try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174 // By always trusting the ssl certificate SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, String authType) { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); connRegistryBuilder.register("https", sslsf); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { e.printStackTrace(); } Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(connRegistry); connectionManager.setMaxTotal(5); connectionManager.setDefaultMaxPerRoute(5); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(requestConfig); clientBuilder.setConnectionManager(connectionManager); clientBuilder.setUserAgent("Cognitio"); client = clientBuilder.build(); }