private static SSLConnectionSocketFactory createSSLConnectionSocketFactory(Path path, char[] password, boolean strict, KeystoreType keystoreType) { try { SSLContextBuilder builder = SSLContexts.custom(); if (path != null) { KeyStore trustStore = KeyStore.getInstance(keystoreType.name()); try (InputStream is = Files.newInputStream(path)) { trustStore.load(is, password); } builder.loadTrustMaterial(trustStore); } else { builder.loadTrustMaterial(null, new TrustEverythingStrategy()); } X509HostnameVerifier verifier; if (strict) { verifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; } else { verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; } return new SSLConnectionSocketFactory(builder.build(), new String[] {"TLSv1", "TLSv1.2"}, null, verifier); } catch (IOException | GeneralSecurityException ex) { throw new RuntimeException("Can't create SSL connection factory", ex); } }
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password)); SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .useTLS() .build(); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); HttpClient httpClient = HttpClientBuilder.create() .disableRedirectHandling() .setDefaultCredentialsProvider(credentialsProvider) .setSSLSocketFactory(connectionFactory) .build(); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); restTemplate.getInterceptors().addAll(interceptors); return restTemplate; }
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException { try { KeyStore keyStore = KeyStoreUtils.createDockerKeyStore(certPath); SSLContext sslContext = SSLContexts.custom() .useTLS() .loadKeyMaterial(keyStore, "docker".toCharArray()) .loadTrustMaterial(keyStore) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build(); } catch (GeneralSecurityException e) { throw new IOException(e); } }
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(); }
public static CloseableHttpClient ceateSSLClient(File keyFile, String protocol, String password){ CloseableHttpClient httpclient = null; try{ KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(keyFile); try { keyStore.load(instream, password.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build(); // Allow TLSv1 protocol only String[] protocols = new String[] {protocol}; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,protocols,null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); }catch(Exception e){ e.printStackTrace(); } return httpclient; }
/** * *@name 获取ssl链接 *@Description *@CreateDate 2015年12月31日下午2:34:40 */ public static SSLConnectionSocketFactory getSSLConnectionSocketFactory(String keyStoreType,String certFilePath,String certPassword) throws Exception{ KeyStore keyStore = KeyStore.getInstance(keyStoreType); // FileInputStream instream = new FileInputStream(new File(certFilePath)); InputStream instream = null; try { instream = new ClassPathResource(certFilePath).getInputStream(); keyStore.load(instream, certPassword.toCharArray()); } finally { instream.close(); } SSLContext sslContext = SSLContexts.custom() .loadKeyMaterial(keyStore, certPassword.toCharArray()) .build(); return new SSLConnectionSocketFactory(sslContext,new String[] { "TLSv1" },null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); }
protected void initBase() { SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); httpRequestConfig = RequestConfig.custom() .setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT) .setCookieSpec(CookieSpecs.BEST_MATCH) .build(); cookieStore = new BasicCookieStore(); httpClient = HttpClientBuilder.create() .setSSLSocketFactory(sslsf) .setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(httpRequestConfig) .build(); localContext = HttpClientContext.create(); }
private ClientHttpRequestFactory createRequestFactory(String host, String username, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password)); SSLContext sslContext = null; try { sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new DirectorException("Unable to configure ClientHttpRequestFactory", e); } SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); // disabling redirect handling is critical for the way BOSH uses 302's HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling() .setDefaultCredentialsProvider(credentialsProvider) .setSSLSocketFactory(connectionFactory).build(); return new HttpComponentsClientHttpRequestFactory(httpClient); }
/** * 初始化SSL证书 * * @return * @throws PaymentException */ private SSLContext initSSLContext() throws PaymentException { // 初始化证书, 证书位置为classes目录 SSLContext sslContext = null; try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream inputStream = new FileInputStream(new File(wxConfig.getMchPKCs())); keyStore.load(inputStream, wxConfig.getMchid().toCharArray()); // Trust own CA and all self-signed certs sslContext = SSLContexts.custom() .loadKeyMaterial(keyStore, wxConfig.getMchid().toCharArray()) .build(); } catch (Exception e) { throw new PaymentException("在进行退款时发生了证书初始化错误.", e); } return sslContext; }
@Bean @Qualifier("hgmRestTemplate") public RestTemplate getHgmHttpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS() .build(); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword())); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(connectionFactory) .setDefaultCredentialsProvider(credentialsProvider).build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(requestFactory); }
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"); } }
private CloseableHttpClient prepareHttpClient() throws NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, KeyStoreException { // for simple http (no https) use this instead: // return HttpClients.createDefault(); FileInputStream fin = new FileInputStream(TRUSTSTORE_PATH); KeyStore ks = KeyStore.getInstance(TRUSTSTORE_TYPE); ks.load(fin, TRUSTSTORE_PASSWORD.toCharArray()); SSLContext sslContext = SSLContexts.custom().useTLS() .loadTrustMaterial(ks).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); }
protected void initBase() { //Initiate SSLSocketFactory. "java.lang.IllegalArgumentException: Item may not be null" error fixed. SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); httpClient = HttpClientBuilder.create() .setSSLSocketFactory(sslsf) .build(); // httpRequestConfig = RequestConfig.custom() // .setSocketTimeout(TIMEOUT) // .setConnectTimeout(TIMEOUT) // .build(); localContext = new BasicHttpContext(); }
public static SSLConnectionSocketFactory createSSLConnectionSocketFactory(File file, String password) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(file); try { trustStore.load(instream, password.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); return sslsf; }
@Override public void init(ZibaseDeviceConfiguration configuration) { this.configuration = configuration; try { // init HTTP client SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (chain, authType) -> true).build(); httpClient = HttpAsyncClients.custom().setSSLContext(sslContext).build(); httpClient.start(); // configure Json parser mapper = new ObjectMapper(); mapper.getFactory().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); token = fetchToken(); // TODO: fetch Zibase devices after init } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { logger.error("Can't initialize SSL engine", e); } }
public ConnectionManager() { loggedIn = false; SSLContext sslContext = SSLContexts.createSystemDefault(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(); pcm.setMaxTotal(100); pcm.setDefaultMaxPerRoute(50); HttpCompressionRequestInterceptor requestInterceptor = new HttpCompressionRequestInterceptor(); HttpCompressionResponseInterceptor responseInterceptor = new HttpCompressionResponseInterceptor(); httpClient = HttpClients.custom() .setConnectionManager(pcm) .setSSLSocketFactory(sslSocketFactory) .addInterceptorFirst(requestInterceptor) .addInterceptorFirst(responseInterceptor) .build(); }
/** * Initializes SSL connection * @return * @throws GeneralSecurityException * @throws IOException */ private CloseableHttpClient initializeConnection() throws InitalizeCommunicationException{ try { if(socketFactory==null){ //Generates a keystore with Latch SSL CA final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final InputStream in = Latch.class.getResourceAsStream("/LatchCA.cer"); final Certificate ca = cf.generateCertificate(in); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); //SSL context with custom keystore final SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore).build(); socketFactory = new SSLConnectionSocketFactory(sslcontext); } //Initialize and configure connection return HttpClients.custom().setSSLSocketFactory(socketFactory).build(); } catch (Exception e) { log.error("Error initializing connection: ", e); throw new InitalizeCommunicationException("Error initializing connection: ", e); } }
private SSLConnectionSocketFactory createSslSocketFactory(Configuration configuration) { X509HostnameVerifier verifier; if (configuration.isApiSslCnCheck()) { verifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; } else { verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; } // Remove SSLv2Hello and SSLv3 from the allowed ciphers list // Java 7u75 disabled them anyway, so usually the MyTimetable server will not support these protocols SSLContext sslContext = SSLContexts.createSystemDefault(); Set<String> enabledProtocols = new HashSet<String>(); for (String s : sslContext.getDefaultSSLParameters().getProtocols()) { if (s.equals("SSLv3") || s.equals("SSLv2Hello")) { continue; } enabledProtocols.add(s); } return new SSLConnectionSocketFactory(sslContext, enabledProtocols.toArray(new String[enabledProtocols.size()]), null, verifier); }
/** * Gets the trusted ssl context. * * @param trustStoreFile the trust store file * @param trustStorePassword the trust store password * @param trustStoreType the trust store type * @return the trusted ssl context */ private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword, final String trustStoreType) { try { if (!trustStoreFile.exists() || !trustStoreFile.canRead()) { throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath()); } final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType); final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray(); try (FileInputStream casStream = new FileInputStream(trustStoreFile)) { casTrustStore.load(casStream, trustStorePasswordCharArray); } final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray); final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null); final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore); final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null); final KeyManager[] keyManagers = { new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager)) }; final TrustManager[] trustManagers = { new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager)) }; final SSLContext context = SSLContexts.custom().useSSL().build(); context.init(keyManagers, trustManagers, null); return context; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } }
/** * Gets the trusted ssl context. * * @param trustStoreFile the trust store file * @param trustStorePassword the trust store password * @param trustStoreType the trust store type * @return the trusted ssl context */ private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword, final String trustStoreType) { try { if (!trustStoreFile.exists() || !trustStoreFile.canRead()) { throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath()); } final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType); final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray(); try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) { casTrustStore.load(casStream, trustStorePasswordCharArray); } final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray); final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null); final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore); final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null); final KeyManager[] keyManagers = { new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager)) }; final TrustManager[] trustManagers = { new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager)) }; final SSLContext context = SSLContexts.custom().useSSL().build(); context.init(keyManagers, trustManagers, null); return context; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } }
/** * 设置双向认证的JKS * * @date 2015年7月17日 * @param keyStore * jks * @return */ public HttpUtils setJKS(KeyStore keyStore) { try { SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(keyStore).build(); socketFactory = new SSLConnectionSocketFactory(sslContext); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return this; }
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输 try { keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码 } catch (Exception e) { e.printStackTrace(); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(keyStore, config.getCertPassword().toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpClient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); //根据默认超时限制初始化requestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build(); hasInit = true; }
@Override public HttpClient getObject() throws Exception { HttpClientBuilder clientBuilder = HttpClients.custom(); HttpRoutePlanner routePlanner = getRoutePlanner(); if( routePlanner != null ) { clientBuilder.setRoutePlanner(routePlanner); } clientBuilder.disableCookieManagement(); clientBuilder.setMaxConnPerRoute(connectionPoolSize); if (insecureSsl) { SSLContext context = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( context, new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientBuilder.setSSLSocketFactory(sslsf); } return clientBuilder.build(); }
protected Registry<ConnectionSocketFactory> createConnectionRegistry(X509HostnameVerifier x509HostnameVerifier, SSLContextParameters sslContextParams) throws GeneralSecurityException, IOException { // create the default connection registry to use RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create(); builder.register("http", PlainConnectionSocketFactory.getSocketFactory()); builder.register("http4", PlainConnectionSocketFactory.getSocketFactory()); if (sslContextParams != null) { builder.register("https", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier)); builder.register("https4", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier)); } else { builder.register("https4", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier)); builder.register("https", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier)); } return builder.build(); }
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(); }
/** * Builds a new SSLContext with the given configuration and allows the uses of * self-signed certificates during testing. */ protected SSLContext buildSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { return SSLContexts.custom() .loadKeyMaterial(buildKeyStore(getKeyStore(), getKeyStorePassword()), getKeyStorePassword().toCharArray()) .loadTrustMaterial(buildKeyStore(getTrustStore(), getTrustStorePassword()), new TrustSelfSignedStrategy()).build(); }
private static SSLContext buildSSLContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslcontext = SSLContexts.custom() .setSecureRandom(new SecureRandom()) .loadTrustMaterial(null, new TrustStrategy() { // ## SHOULD FIRE OVER-PERMISSIVE TRUST MANAGER public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }) .build(); return sslcontext; }
private SSLConnectionSocketFactory getLenientSslSocketFactory() { SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; }
private SSLContext createSSLContext() { try { return SSLContexts.custom().loadTrustMaterial(createKeyStore(), new TrustSelfSignedStrategy()).build(); } catch (Exception e) { throw new RuntimeException("Could not create SSL context", e); } }
private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException { HttpClientBuilder _builder = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(__connectionTimeout) .setSocketTimeout(__connectionTimeout) .setConnectionRequestTimeout(__connectionTimeout).build()); if (__socketFactory == null) { __socketFactory = new SSLConnectionSocketFactory( SSLContexts.custom().useSSL().build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } return _builder.setSSLSocketFactory(__socketFactory).build(); }
public static void getCodeImage(int num) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("D:/tmp/pbccrc.store")); try { trustStore.load(instream, "123456".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // CloseableHttpClient client = // HttpClients.custom().setSSLSocketFactory(sslsf).build(); CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet("http://www.189.cn/dqmh/createCheckCode.do?method=checkLoginCode&date=" + Math.random()); get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"); for (int i = 0; i < num; i++) { File file = new File("D:/tmp/images2/" + i + ".jpg"); CloseableHttpResponse response = client.execute(get); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), file); response.close(); System.out.println(file.getAbsolutePath()); Thread.sleep(100); } }
@Test public void sslDiscoveryTest() throws IOException, JAXBException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, URISyntaxException { final String serverUrl = "https://127.0.0.1:8443/services/discovery/"; // Prepare the TLS objects necessary for SSL connection. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .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(); // Create a Taxii Client with the HttpClient and TaxiiXml objects. HttpClient taxiiClient = new HttpClient(httpClient); // Prepare the message to send. DiscoveryRequest dr = factory.createDiscoveryRequest() .withMessageId(MessageHelper.generateMessageId()); // Call the service Object responseObj = taxiiClient.callTaxiiService(new URI(serverUrl), dr); if (debug) { System.out.println(taxiiXml.marshalToString(dr, true)); System.out.println(taxiiXml.marshalToString(responseObj, true)); } assertTrue("Received Discovery Response", (responseObj instanceof DiscoveryResponse)); }
@Test public void failedSslDiscoveryTest() throws IOException, JAXBException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, URISyntaxException { final String endpoint = "https://127.0.0.1:8443/services/discovery/"; /* The below configures the client to accept self-signed certificates. */ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, "nopassword".toCharArray()); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .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(); HttpClient taxiiClient = new HttpClient(httpClient); // Prepare the message to send. DiscoveryRequest dr = factory.createDiscoveryRequest() .withMessageId(MessageHelper.generateMessageId()); Object responseObj = null; responseObj = taxiiClient.callTaxiiService(new URI(endpoint), dr); if (debug) { System.out.println(taxiiXml.marshalToString(dr, true)); if (null != responseObj) { System.out.println(taxiiXml.marshalToString(responseObj, true)); } } assertTrue("Received Status Message", (responseObj instanceof StatusMessage)); }
private HttpClient createHttpClient(ConnectionConfig config) { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(config.getConnectionTimeoutMs()) .setSocketTimeout(config.getSocketTimeoutMs()) .build(); RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create(); registryBuilder.register("http", new PlainConnectionSocketFactory()); if (config.isHttpsEnabled()) { SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register("https", sslsf); } connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnection()); connectionManager.setMaxTotal(config.getMaxConnection()); HttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)) .build(); return httpClient; }
/** * Creates a new instance. * * @param x509TrustEngine X.509 trust engine used to validate the TLS certificate presented by the proxy * callback endpoint. */ public PkixProxyAuthenticator(@Nonnull TrustEngine<X509Credential> x509TrustEngine) { Constraint.isNotNull(x509TrustEngine, "Trust engine cannot be null"); try { SSLContext sslContext = SSLContexts.custom() .useTLS() .loadTrustMaterial(null, new TrustEngineTrustStrategy(x509TrustEngine)) .build(); socketFactory = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { throw new RuntimeException("SSL initialization error", e); } }
/** * Builds the HTTP client to connect to the server. * * @param trustSelfSigned <tt>true</tt> if the client should accept * self-signed certificates * @return a new client instance */ private CloseableHttpClient buildClient(boolean trustSelfSigned) { try { // if required, define custom SSL context allowing self-signed certs SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault() : SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); // set timeouts for the HTTP client int globalTimeout = readFromProperty("bdTimeout", 100000); int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout); int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout); int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout); RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build(); // configure caching CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000) .setMaxObjectSize(2 * 1024 * 1024).build(); // configure connection pooling PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder .<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext)).build()); int connectionLimit = readFromProperty("bdMaxConnections", 40); // there's only one server to connect to, so max per route matters connManager.setMaxTotal(connectionLimit); connManager.setDefaultMaxPerRoute(connectionLimit); // create the HTTP client return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig) .setConnectionManager(connManager).build(); } catch (GeneralSecurityException e) { throw new InternalConfigurationException("Failed to set up SSL context", e); } }