List of usage examples for org.apache.http.conn.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJsonWithHTTPS() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("https.enabled", "true"); properties.put("https.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("https.hostname", "localhost"); properties.put("https.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {/*www.j a v a2 s. c o m*/ context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build()); RestTemplate httpClient = new RestTemplate(requestFactory); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")), "changeit".toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHTTPServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }//from w w w .j ava2 s . c om 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:hello.MyPostHTTP.java
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { SSLContextBuilder builder = SSLContexts.custom(); final String trustFilename = service.getTrustStoreFile(); if (trustFilename != null) { final KeyStore truststore = KeyStore.getInstance(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); }/*from ww w . j av a2s . c om*/ builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } final String keyFilename = service.getKeyStoreFile(); if (keyFilename != null) { final KeyStore keystore = KeyStore.getInstance(service.getKeyStoreType()); try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) { keystore.load(in, service.getKeyStorePassword().toCharArray()); } builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray()); } final SSLContext sslContext = builder.build(); return sslContext; }
From source file:br.com.intercomex.ws.GnreLoteRecepcao.java
@WebMethod(operationName = "processarSimples") public String processarSimples(@WebParam(name = "gnreDadosMsg") Object TLoteGNRE) { br.gov.pe.gnre.TRetLoteGNRE retorno = null; String recibo = null;// w ww .ja v a 2 s . co m try { loadConfig(); XmlUtil util = new XmlUtil(); //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> //String gnreDadosMsgSTR= util.convertToXml(TLoteGNRE, br.gov.pe.gnre.TLoteGNRE.class); System.out.println("PARAMETRO envio ==== " + TLoteGNRE); String gnreDadosMsgSTR = util.nodeToString((Node) TLoteGNRE); String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreLoteRecepcao\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + "<soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsgSTR + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + XML_DATA); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", action)); StringEntity s = new StringEntity(XML_DATA, "UTF-8"); httpPost.setEntity(s); FileInputStream instream = null; FileInputStream instreamTrust = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente)); keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado)); trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray()); SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore); builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray()); SSLContext sslcontext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build(); System.out.println("executing request" + httpPost.getRequestLine()); HttpResponse response = httpclientSLL.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); String retornoStr = EntityUtils.toString(entity); System.out.println("Response " + retornoStr); retorno = util.getTRetLoteGNRE(retornoStr); recibo = util.getRecibo(retornoStr); System.out.println("ResponseOBJ " + retorno.getAmbiente()); recibo = retorno.getRecibo().getNumero(); } if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (CertificateException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } return recibo; }
From source file:se.skltp.adapterservices.druglogistics.dosdispensing.RetryComponent.java
private Registry<ConnectionSocketFactory> setupSSLSocketFactory() { try {//from w w w . j a v a 2s. c om KeyStore keystore = loadKeystore(keystorePath, keystorePassword.toCharArray(), keystoreType); char[] keyPassword = keystorePassword.toCharArray(); KeyStore truststore = loadKeystore(truststorePath, truststorePassword.toCharArray(), truststoreType); SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, keyPassword) .loadTrustMaterial(truststore).build(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); return socketFactoryRegistry; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
protected SSLConnectionSocketFactory getSSLConnectionSocketFactory() { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); SSLContext sslContext = null; try {//from w w w . j ava2s . co m sslContextBuilder.loadTrustMaterial(_keyStore); sslContext = sslContextBuilder.build(); sslContext.init(null, new TrustManager[] { new X509TrustManagerImpl() }, null); } catch (Exception e) { throw new RuntimeException(e); } return new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); }
From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java
protected SSLContext createSSLContext() { if (!trustAllSSLCertificates) { return null; }//w ww. j av a 2 s . c o m SSLContext sslcontext; try { sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }).build(); } catch (Exception e) { throw new CollectorException("Cannot create SSL context trusting all certificates.", e); } return sslcontext; }
From source file:net.yoomai.wechat.capabilities.PaymentCapability.java
/** * ?SSL?/*from w ww .j a v a2 s . c om*/ * * @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; }
From source file:fi.csc.shibboleth.mobileauth.impl.authn.AuthenticateMobile.java
/** * This method will create CloseableHttpClient with client certificate authentication * // w ww. j av a2 s . co m * @return CloseableHttpClient * @throws KeyStoreException * @throws RuntimeException */ private CloseableHttpClient createHttpClient() throws KeyStoreException, RuntimeException { KeyStore trustStore = KeyStore.getInstance(trustStoreType); KeyStore clientStore = KeyStore.getInstance(keystoreType); try { trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray()); clientStore.load(new FileInputStream(keystorePath), keystorePasswd.toCharArray()); } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new RuntimeException("Cannot load key/trust stores", e); } final SSLConnectionSocketFactory socketFactory; try { final SSLContext sslContext = SSLContexts.custom().useTLS() .loadKeyMaterial(clientStore, keystorePasswd.toCharArray()).loadTrustMaterial(trustStore) .build(); socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { throw new RuntimeException("SSL initialization error", e); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); log.debug("Created httpClient"); return HttpClients.custom().setConnectionManager(connectionManager).build(); }
From source file:br.com.intercomex.ws.GnreResultadoLote.java
@WebMethod(operationName = "consultarSimplesHomoloacao") public String consultarSimplesHomoloacao(@WebParam(name = "nrRecibo") String nrRecibo) { String url_HML = "https://www.gnre-h.pe.gov.br/gnreWS/services/GnreResultadoLote?wsdl"; String action_HML = "http://www.gnre-h.pe.gov.br/gnreWS/services/GnreResultadoLote/consultar"; String resultado = null;/*from www. ja v a 2 s. com*/ TResultLoteGNRE retorno = null; loadConfig(); try { //<TConsLote_GNRE xmlns="http://www.gnre.pe.gov.br"><ambiente>1</ambiente><numeroRecibo>2012314940</numeroRecibo></TConsLote_GNRE> String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreResultadoLote\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + " <soap:Body><gnr:gnreDadosMsg><TConsLote_GNRE xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>2</ambiente><numeroRecibo>" + nrRecibo + "</numeroRecibo></TConsLote_GNRE></gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + XML_DATA); HttpPost httpPost = new HttpPost(url_HML); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", action_HML)); StringEntity s = new StringEntity(XML_DATA, "UTF-8"); httpPost.setEntity(s); FileInputStream instream = null; FileInputStream instreamTrust = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente)); keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado)); trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray()); SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore); builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray()); SSLContext sslcontext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build(); System.out.println("executing request" + httpPost.getRequestLine()); System.out.println("Conteudo envio ==== " + XML_DATA); HttpResponse response = httpclientSLL.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); String str = EntityUtils.toString(entity); System.out.println(str); XmlUtil util = new XmlUtil(); retorno = util.getTResultLoteGNRE(str); resultado = retorno.getResultado(); } if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (CertificateException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } return resultado; }