List of usage examples for org.apache.http.conn.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:test.SAMLAttributeQueryExample.java
/** * Build the HTTP client./*w w w. ja v a2 s .c o m*/ * * @param idpCertificateFile path to idp certificate file * @param clientPrivateKeyFile path to client private key file * @param clientCertificateFile path to client certificate file * @return the HTTP client * @throws Exception if an error occurs */ @Nonnull public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile, @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile) throws Exception { X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("idp", idpCert); PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile); X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert }); SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(trustStore); sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray()); SSLContext sslcontext = sslContextBuilder.build(); CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build(); return httpClient; }
From source file:com.vmware.bdd.plugin.ironfan.impl.RolePackageMapping.java
@SuppressWarnings("deprecation") private String readDistroManifest() throws Exception { File manifestFile = new File(DISTRO_MANIFEST_FILE_PATH); if (manifestFile.exists()) { // The manifest file is on the local server. // No need to reload the file if it's not modified. if (lastModified != manifestFile.lastModified()) { lastModified = manifestFile.lastModified(); logger.info("last modified date of manifest file changed. Reloading manifest."); } else {/* w w w.ja v a 2s.c o m*/ return null; } } BufferedReader in = null; DefaultHttpClient httpclient = new DefaultHttpClient(); try { SSLContext sslContext = SSLContexts.custom().useTLS().build(); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return; } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return; } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, null); TlsClientConfiguration tlsConfiguration = new TlsClientConfiguration(); SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, tlsConfiguration.getSslProtocols(), tlsConfiguration.getCipherSuites(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet httpget = new HttpGet(new URI(distrosManifestUrl)); if (eTag != null) { httpget.addHeader("If-None-Match", eTag); } logger.info("executing request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); if (!manifestFile.exists()) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { return null; } else { logger.debug("ETag of manifest file changed. Reloading manifest."); eTag = response.getFirstHeader("ETag").getValue(); ; } } HttpEntity entity = response.getEntity(); in = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer sb = new StringBuffer(); String line; while ((line = in.readLine()) != null) { sb.append(line); } EntityUtils.consume(entity); return sb.toString(); } finally { httpclient.getConnectionManager().shutdown(); if (in != null) { in.close(); } } }
From source file:org.wisdom.framework.vertx.ServerTest.java
/** * This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication. *//*from w w w. j a v a2s .c o m*/ @Test public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException { FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", false).put("authentication", false).build()); FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", false).build()); FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", true).build()); // Server HTTPS File root = new File(""); final File serverKeyStore = new File( root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks"); assertThat(serverKeyStore).isFile(); when(application.get("https.keyStore")).thenReturn(serverKeyStore.getAbsolutePath()); when(application.get("https.trustStore")) .thenReturn(new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks") .getAbsolutePath()); when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getConfiguration("vertx.servers")) .thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2, "s3", s3))); Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { return ok("Alright"); } }; Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index"); when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route); wisdom.start(); waitForStart(wisdom); waitForHttpsStart(wisdom); assertThat(wisdom.servers).hasSize(3); // Check rendering for (Server server : wisdom.servers) { String r; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks"); trustStore.load(instream, "wisdom".toCharArray()); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .loadKeyMaterial(trustStore, "wisdom".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1", "SSLv3" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); if (server.ssl()) { HttpGet httpget = new HttpGet("https://localhost:" + server.port()); final CloseableHttpResponse response = httpclient.execute(httpget); r = EntityUtils.toString(response.getEntity()); } else { r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port()).execute() .returnContent().asString(); } assertThat(r).isEqualToIgnoringCase("Alright"); } }
From source file:br.com.intercomex.ws.GnreLoteRecepcao.java
/** * This is a sample web service operation *//*from ww w .ja v a 2 s . co m*/ @WebMethod(operationName = "processar") public br.gov.pe.gnre.TRetLoteGNRE processar(@WebParam(name = "gnreDadosMsg") TLoteGNRE TLoteGNRE) { br.gov.pe.gnre.TRetLoteGNRE retorno = null; 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); } 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.floragunn.searchguard.httpclient.HttpClient.java
private final CloseableHttpClient createHTTPClient() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { // basic auth // pki auth/*from w ww. j a v a2 s . c om*/ // kerberos auth final org.apache.http.impl.client.HttpClientBuilder hcb = HttpClients.custom(); if (ssl) { final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (log.isTraceEnabled()) { log.trace("Configure HTTP client with SSL"); } if (trustStore != null) { final KeyStore myTrustStore = KeyStore .getInstance(trustStore.getName().endsWith("jks") ? "JKS" : "PKCS12"); myTrustStore.load(new FileInputStream(trustStore), truststorePassword == null || truststorePassword.isEmpty() ? null : truststorePassword.toCharArray()); sslContextbBuilder.loadTrustMaterial(myTrustStore); } if (keystore != null) { final KeyStore keyStore = KeyStore .getInstance(keystore.getName().endsWith("jks") ? "JKS" : "PKCS12"); keyStore.load(new FileInputStream(keystore), keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); sslContextbBuilder.loadKeyMaterial(keyStore, keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.1", "TLSv1.2" }, null, verifyHostnames ? SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } /*if (keytab != null) { //System.setProperty("java.security.auth.login.config", "login.conf"); //System.setProperty("java.security.krb5.conf", "krb5.conf"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new LoginSPNegoSchemeFactory(true); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); hcb.setDefaultCredentialsProvider(credsProvider); }*/ if (basicCredentials != null) { hcb.setDefaultHeaders( Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials))); } return hcb.build(); }
From source file:cn.org.once.cstack.utils.JSONClient.java
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException { try {// www. ja va2s . c om 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); } }
From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps( RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) throws DSSException { try {//from w w w . ja v a 2 s .c om SSLContext sslContext = null; if (StringUtils.isEmpty(sslKeystorePath)) { LOG.debug("Use default SSL configuration"); sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(sslContext); } else { LOG.debug("Use specific SSL configuration with keystore"); FileInputStream fis = new FileInputStream(new File(sslKeystorePath)); KeyStore keystore = KeyStore.getInstance(sslKeystoreType); keystore.load(fis, sslKeystorePassword.toCharArray()); IOUtils.closeQuietly(fis); sslContext = SSLContexts.custom().loadTrustMaterial(keystore).useTLS().build(); } final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext); return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory); } catch (Exception e) { throw new DSSException(e); } }
From source file:org.apache.solr.util.SSLTestConfig.java
/** * Builds a new SSLContext for jetty servers which have been configured based on the settings of * this object.//from w ww . j av a 2s . c om * * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking * due to lack of entropy, also explicitly allows the use of self-signed * certificates (since that's what is almost always used during testing). * almost always used during testing). */ public SSLContext buildServerSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { assert isSSLMode(); SSLContextBuilder builder = SSLContexts.custom(); builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE); builder.loadKeyMaterial(buildKeyStore(keyStore, getKeyStorePassword()), getKeyStorePassword().toCharArray()); if (isClientAuthMode()) { builder.loadTrustMaterial(buildKeyStore(trustStore, getTrustStorePassword()), new TrustSelfSignedStrategy()).build(); } return builder.build(); }
From source file:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java
private void startHttpClient() { if (httpClient != null) { // http client is already started return;/* ww w.java2 s . c o m*/ } // limit max number of async requests in sequential mode, 0 means "use // default limit" int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0; if (!disableCertificateValidation) { // create an http client that validates certificates httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).build(); } else { // create strategy that accepts all certificates TrustStrategy acceptingTrustStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] certificate, String type) { return true; } }; SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal) .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) .setSSLContext(sslContext).build(); } catch (Exception e) { } } httpClient.start(); }
From source file:br.com.intercomex.ws.EnviarLoteService.java
private String processarServico(Object TLoteGNRE, String urlParam, String actionParam) { br.gov.pe.gnre.TRetLoteGNRE retorno = null; String recibo = null;//from w w w . j av a 2 s.c om try { loadConfig(); XmlUtil util = new XmlUtil(); //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> System.out.println("PARAMETRO envio ==== " + TLoteGNRE); //String gnreDadosMsgSTR= util.convertToXml(TLoteGNRE, br.gov.pe.gnre.TLoteGNRE.class); //String gnreDadosMsgSTR= 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(urlParam); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", actionParam)); 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 " + recibo); } 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; }