List of usage examples for org.apache.http.ssl SSLContextBuilder loadTrustMaterial
public SSLContextBuilder loadTrustMaterial(final URL url, final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException
From source file:ph.com.globe.connect.HttpRequest.java
/** * Send post request to the specified url. * /* w w w . j av a2 s .c o m*/ * @return CloseableHttpResponse * @throws HttpRequestException http request exception */ public CloseableHttpResponse sendPost() throws HttpRequestException { // try building up try { // initialize ssl context builder SSLContextBuilder builder = new SSLContextBuilder(); // set trust self signed strategy builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // initialize ssl socket connection factory SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build()); // default http client CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); // create request method HttpPost post = new HttpPost(this.url); // set default user agent post.setHeader("User-Agent", this.USER_AGENT); // set default content type post.setHeader("Content-Type", this.CONTENT_TYPE); // convert data to json string JSONObject data = new JSONObject(this.data); try { // set the string entity StringEntity entity = new StringEntity(data.toString()); // set post data post.setEntity(entity); } catch (UnsupportedEncodingException e) { // throw exception throw new HttpRequestException(e.getMessage()); } // try request try { // execute request and get the response CloseableHttpResponse response = client.execute(post); return response; } catch (IOException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } }
From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java
/** * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds * * @param keyPair the keypair to generate the csr for * @throws IOException if there is a problem during the process * @return the resulting certificate chain */// ww w .j ava 2 s .c o m public X509Certificate[] perform(KeyPair keyPair) throws IOException { try { List<X509Certificate> certificates = new ArrayList<>(); HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.useProtocol("TLSv1.2"); // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory( sslContextBuilder.build(), caHostname, certificates)); String jsonResponseString; int responseCode; try (CloseableHttpClient client = httpClientBuilder.build()) { JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm); TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest( TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request)); HttpPost httpPost = new HttpPost(); httpPost.setEntity( new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest))); if (logger.isInfoEnabled()) { logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port); } try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) { jsonResponseString = IOUtils.toString( new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8); responseCode = response.getStatusLine().getStatusCode(); } } if (responseCode != Response.SC_OK) { throw new IOException( RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString); } if (certificates.size() != 1) { throw new IOException(EXPECTED_ONE_CERTIFICATE); } TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class); if (!tlsCertificateAuthorityResponse.hasHmac()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC); } X509Certificate caCertificate = certificates.get(0); byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey()); if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) { throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE); } if (!tlsCertificateAuthorityResponse.hasCertificate()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE); } X509Certificate x509Certificate = TlsHelper .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate())); x509Certificate.verify(caCertificate.getPublicKey()); if (logger.isInfoEnabled()) { logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal()); } return new X509Certificate[] { x509Certificate, caCertificate }; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
From source file:com.intuit.tank.httpclient4.TankHttpClient4.java
/** * no-arg constructor for client//from w w w . j a v a2s . c o m */ public TankHttpClient4() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } catch (Exception e) { LOG.error("Error setting accept all: " + e, e); } httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000) .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true) .setMaxRedirects(100).build(); // Make sure the same context is used to execute logically related // requests context = HttpClientContext.create(); context.setCredentialsProvider(new BasicCredentialsProvider()); context.setCookieStore(new BasicCookieStore()); context.setRequestConfig(requestConfig); }
From source file:org.mycontroller.restclient.core.RestHttpClient.java
private CloseableHttpClient getHttpClientTrustAll() { SSLContextBuilder builder = new SSLContextBuilder(); try {// w ww.j ava2 s . c om KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); builder.loadTrustMaterial(keyStore, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new AnyHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(customRequestConfig) .build(); } catch (Exception ex) { _logger.error("Exception, ", ex); throw new RuntimeException("Unable to create trust ANY http client. Error: " + ex.getMessage()); } }
From source file:org.ulyssis.ipp.publisher.HttpServerPublisher.java
private SSLContext sslContext() { try {//from w w w.j a v a2s . com KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType()); cks.load(new FileInputStream(options.getKeystore().get().toFile()), options.getKeystorePass().toCharArray()); SSLContextBuilder builder = SSLContexts.custom(); if (options.getTruststore().isPresent()) { KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType()); tks.load(new FileInputStream(options.getTruststore().get().toFile()), options.getTruststorePass().toCharArray()); builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy()); } return builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()).build(); } catch (Exception e) { // TODO: DO SOMETHING WITH THE EXCEPTION! LOG.error("Exception", e); } return null; }
From source file:de.elomagic.maven.http.HTTPMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {/*w w w . j av a 2 s. c om*/ Executor executor; if (httpsInsecure) { getLog().info("Accepting unsecure HTTPS connections."); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustAllStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( sfr); connectionManager.setDefaultMaxPerRoute(100); connectionManager.setMaxTotal(200); connectionManager.setValidateAfterInactivity(1000); HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager) .build(); executor = Executor.newInstance(httpClient); } catch (Exception ex) { throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex); } } else { executor = Executor.newInstance(); } Settings settings = session.getSettings(); if (StringUtils.isNotBlank(serverId)) { Server server = settings.getServer(serverId); if (server == null) { throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml"); } getLog().debug("ServerId: " + serverId); executor.auth(server.getUsername(), server.getPassword()); } Request request = createRequestMethod(); request.setHeader("Accept", accept); if (httpHeaders != null) { for (Entry<String, String> entry : httpHeaders.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (formParams != null) { Form form = Form.form(); for (Entry<String, String> entry : formParams.entrySet()) { form.add(entry.getKey(), entry.getValue()); } } if (fromFile != null) { if (!fromFile.exists()) { throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist."); } if (StringUtils.isBlank(contentType)) { contentType = Files.probeContentType(fromFile.toPath()); } getLog().debug("From file: " + fromFile); getLog().debug("Upload file size: " + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue())); getLog().debug("Content type: " + contentType); if (StringUtils.isBlank(contentType)) { request.body(new FileEntity(fromFile)); } else { request.body(new FileEntity(fromFile, ContentType.create(contentType))); } } getLog().info(method + " " + url); Response response = executor.execute(request); handleResponse(response); } catch (Exception ex) { getLog().error(ex); if (failOnError) { throw new MojoExecutionException(ex.getMessage(), ex); } else { getLog().info("Fail on error is disabled. Continue execution."); } } }
From source file:com.thinkbiganalytics.nifi.v2.core.metadata.MetadataProviderSelectorService.java
/** * Taken from NiFi GetHttp Processor/*ww w . j a v a2 s . c om*/ */ private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { final SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); if (StringUtils.isNotBlank(service.getTrustStoreFile())) { final KeyStore truststore = KeyStore.getInstance(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); } sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } if (StringUtils.isNotBlank(service.getKeyStoreFile())) { final KeyStore keystore = KeyStore.getInstance(service.getKeyStoreType()); try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) { keystore.load(in, service.getKeyStorePassword().toCharArray()); } sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray()); } sslContextBuilder.useProtocol(service.getSslAlgorithm()); return sslContextBuilder.build(); }
From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java
private void configureTrustMaterial(final SSLContextBuilder sslBuilder) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, NoSuchProviderException { final KeyStore truststore = loadStore(sslConfig.getTrustStore(), sslConfig.getTrustStorePassword(), sslConfig.getTrustStoreType(), sslConfig.getTrustStoreProvider()); if (truststore != null) { sslBuilder.loadTrustMaterial(truststore, null); }/*from w ww.j a v a2s.c o m*/ }
From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java
private CloseableHttpClient buildHttpClient() { KeyStore keyStore = null;/*from ww w. ja va2 s . c o m*/ KeyStore trustStore = null; FileInputStream instreamKeystore = null; FileInputStream instreamTruststore = null; try { keyStore = KeyStore.getInstance("jks"); instreamKeystore = new FileInputStream(keystorePath); keyStore.load(instreamKeystore, keystorePassword.toCharArray()); if (truststorePath != null && !truststorePath.isEmpty()) { trustStore = KeyStore.getInstance("jks"); instreamTruststore = new FileInputStream(truststorePath); trustStore.load(instreamTruststore, truststorePassword.toCharArray()); } } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (CertificateException e) { log.error("Threw exception", e); return null; } catch (IOException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } finally { try { if (instreamKeystore != null) { instreamKeystore.close(); } if (instreamTruststore != null) { instreamTruststore.close(); } } catch (IOException e) { log.error("Threw exception", e); } } // Trust own CA and all self-signed certs SSLContext sslcontext; try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); // If you have a trust store - should only be needed when the site we contact use self-signed certificates. if (trustStore != null) { sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); sslcontext = sslContextBuilder.build(); } catch (KeyManagementException e) { log.error("Threw exception", e); return null; } catch (UnrecoverableKeyException e) { log.error("Threw exception", e); return null; } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);/*from ww w .j av a 2s. com*/ if (registry == null) { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; break; } } X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers(); if (acceptedIssuers != null) { // If this is null, something is really wrong... int issuerNum = 1; for (X509Certificate cert : acceptedIssuers) { trustStore.setCertificateEntry("issuer" + issuerNum, cert); issuerNum++; } } else { LOG.log(Level.INFO, "Didn't find any new certificates to trust."); } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts))); SSLContext sslContext = sslContextBuilder.build(); SSLContext.setDefault(sslContext); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts))); this.registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory).build(); } return new PoolingHttpClientConnectionManager(registry); }