List of usage examples for org.apache.http.conn.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:br.com.intercomex.ws.GnreConfigUF.java
/** * This is a sample web service operation *//*from w w w . j a v a 2 s .c o m*/ @WebMethod(operationName = "consultar") public String consultar(@WebParam(name = "gnreDadosMsg") TConsultaConfigUf gnreDadosMsg) { String retorno = null; loadConfig(); try { //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreConfigUF\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + gnreDadosMsg); 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()); retorno = EntityUtils.toString(response.getEntity()); System.out.println(retorno); } 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 retorno; }
From source file:com.enioka.jqm.tools.JettyTest.java
@Test public void testSslClientCert() throws Exception { Helpers.setSingleParam("enableWsApiSsl", "true", em); Helpers.setSingleParam("disableWsApi", "false", em); Helpers.setSingleParam("enableWsApiAuth", "false", em); addAndStartEngine();/*ww w . j a v a 2 s. c om*/ // Launch a job so as to be able to query its status later CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar", TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true, em); JobRequest j = new JobRequest("MarsuApplication", "TestUser"); int i = JqmClientFactory.getClient().enqueue(j); TestHelpers.waitFor(1, 10000, em); // Server auth against trusted CA root certificate KeyStore trustStore = KeyStore.getInstance("JKS"); FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks")); try { trustStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } // Client auth JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert", "./conf/client.cer"); KeyStore clientStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File("./conf/client.pfx")); try { clientStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build(); int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class) .setParameter("i", TestHelpers.node.getId()).getSingleResult(); HttpUriRequest rq = new HttpGet( "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i); CloseableHttpResponse rs = cl.execute(rq); Assert.assertEquals(200, rs.getStatusLine().getStatusCode()); rs.close(); cl.close(); }
From source file:net.shibboleth.idp.cas.proxy.impl.HttpClientProxyAuthenticator.java
private CloseableHttpClient createHttpClient(final TrustEngine<? super X509Credential> x509TrustEngine) { final SSLConnectionSocketFactory socketFactory; try {/*w w w . jav a2s. c om*/ final SSLContext sslContext = SSLContexts.custom().useTLS() .loadTrustMaterial(null, new TrustEngineTrustStrategy(x509TrustEngine)).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); } catch (Exception e) { throw new RuntimeException("SSL initialization error", e); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTPS_SCHEME, socketFactory).build(); final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); return HttpClients.custom().setConnectionManager(connectionManager).build(); }
From source file:common.rest.client.transport.HttpClientSSLKeyStore.java
/** * Constructs the {@link org.apache.http.conn.socket.ConnectionSocketFactory} according to the options specified during the * construction time. The returned instance can be used to register an <b><tt>https</tt></b> * sheme in the {@link org.apache.http.conn.socket.ConnectionSocketFactory} while costructing an Apache HTTP client. * * @return <tt>SSLSocketFactory</tt> instance *//*w ww . j av a2s .c o m*/ public LayeredConnectionSocketFactory getSocketFactory() { // @formatter:off final X509HostnameVerifier hostnameVerifier = m_disableHostnameVerifier ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; // @formatter:on try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (m_keyStore != null) { // this key store must contain the key/cert of the client sslContextBuilder.loadKeyMaterial(m_keyStore, m_keyStorePassword.toCharArray()); } if (m_trustStore != null) { // this key store must contain the certs needed and trusted to verify the servers cert sslContextBuilder.loadTrustMaterial(m_trustStore); } return new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier); } catch (Exception e) { throw new IllegalStateException("Failed to create SSL Socket Factory", e); } }
From source file:com.hybris.datahub.outbound.utils.RestTemplateUtil.java
private LayeredConnectionSocketFactory setUpSSL() { LayeredConnectionSocketFactory sslSF = null; try {//from w w w .j a v a 2 s .co m final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final SSLContext sslContext = SSLContexts.custom().useTLS() .loadTrustMaterial(trustStore, new AnyTrustStrategy()).build(); sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (final Exception e) { LOGGER.error(e.getMessage()); } return sslSF; }
From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java
protected final CloseableHttpClient getHTTPClient() throws Exception { final HttpClientBuilder hcb = HttpClients.custom(); if (enableHTTPClientSSL) { log.debug("Configure HTTP client with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHTTPServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }/*from w w w . j a v a2 s. c o m*/ if (sendHTTPClientCertificate) { sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); String[] protocols = null; if (enableHTTPClientSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); return hcb.build(); }
From source file:com.tremolosecurity.scale.config.ScaleCommonConfig.java
@PostConstruct public void init() { try {/* w w w.jav a2 s .co m*/ ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String logPath = null; try { logPath = InitialContext.doLookup("java:comp/env/scaleLog4jPath"); } catch (NamingException ne) { try { logPath = InitialContext.doLookup("java:/env/scaleLog4jPath"); } catch (NamingException ne2) { logPath = null; } } if (logPath == null) { Properties props = new Properties(); props.put("log4j.rootLogger", "info,console"); //props.put("log4j.appender.console","org.apache.log4j.RollingFileAppender"); //props.put("log4j.appender.console.File","/home/mlb/myvd.log"); props.put("log4j.appender.console", "org.apache.log4j.ConsoleAppender"); props.put("log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); props.put("log4j.appender.console.layout.ConversionPattern", "[%d][%t] %-5p %c{1} - %m%n"); PropertyConfigurator.configure(props); } else { if (logPath.startsWith("WEB-INF/")) { org.apache.log4j.xml.DOMConfigurator.configure(context.getRealPath(logPath)); } else { org.apache.log4j.xml.DOMConfigurator.configure(logPath); } } logger = Logger.getLogger(ScaleCommonConfig.class.getName()); logger.info("Initializing Scale " + version); String configPath = null; try { configPath = InitialContext.doLookup("java:comp/env/scaleConfigPath"); } catch (NamingException ne) { try { configPath = InitialContext.doLookup("java:/env/scaleConfigPath"); } catch (NamingException ne2) { configPath = null; } } if (configPath == null) { configPath = "WEB-INF/scaleConfig.xml"; logger.warn("No configuraiton path found - Loading configuration from '" + configPath + "'"); } else { logger.info("Loading configuration from '" + configPath + "'"); } InputStream in = null; if (configPath.startsWith("WEB-INF")) { in = new ByteArrayInputStream(ScaleCommonConfig .includeEnvironmentVariables(context.getRealPath("/" + configPath)).getBytes("UTF-8")); } else { in = new ByteArrayInputStream( ScaleCommonConfig.includeEnvironmentVariables(configPath).getBytes("UTF-8")); } JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.scale.config.xml"); Unmarshaller unmarshaller = jc.createUnmarshaller(); Object obj = unmarshaller.unmarshal(in); JAXBElement<ScaleCommonConfigType> scaleConfig = (JAXBElement<ScaleCommonConfigType>) obj; this.scaleConfig = scaleConfig.getValue(); String ksPath = this.scaleConfig.getServiceConfiguration().getKeyStorePath(); String ksPass = this.scaleConfig.getServiceConfiguration().getKeyStorePassword(); in = null; if (ksPath.startsWith("WEB-INF")) { in = context.getResourceAsStream("/" + ksPath); } else { in = new FileInputStream(ksPath); } this.tlsKeys = KeyStore.getInstance("JKS"); this.tlsKeys.load(in, ksPass.toCharArray()); this.sslctx = SSLContexts.custom().loadTrustMaterial(this.tlsKeys) .loadKeyMaterial(this.tlsKeys, ksPass.toCharArray()).build(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.couchbase.jdbc.core.ProtocolImpl.java
public ProtocolImpl(String url, Properties props) { if (props.containsKey(ConnectionParameters.USER)) { user = props.getProperty(ConnectionParameters.USER); }/* w w w . jav a 2 s . c o m*/ if (props.containsKey(ConnectionParameters.PASSWORD)) { password = props.getProperty(ConnectionParameters.PASSWORD); } if (props.containsKey("credentials")) { credentials = props.getProperty("credentials"); } this.url = url; setConnectionTimeout(props.getProperty(ConnectionParameters.CONNECTION_TIMEOUT)); if (props.containsKey(ConnectionParameters.SCAN_CONSISTENCY)) { scanConsistency = props.getProperty(ConnectionParameters.SCAN_CONSISTENCY); } requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setConnectTimeout(connectTimeout) .setSocketTimeout(connectTimeout).build(); if (props.containsKey(ConnectionParameters.ENABLE_SSL) && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true")) { SSLContextBuilder builder = SSLContexts.custom(); try { 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(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig) .build(); ssl = true; } catch (Exception ex) { logger.error("Error creating ssl client", ex); } } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); } }