/** * Key store 类型HttpClient * * @param keystore keystore * @param keyPassword keyPassword * @param supportedProtocols supportedProtocols * @param timeout timeout * @param retryExecutionCount retryExecutionCount * @return CloseableHttpClient */ public static CloseableHttpClient createKeyMaterialHttpClient( KeyStore keystore, String keyPassword, String[] supportedProtocols, int timeout, int retryExecutionCount) { try { SSLContext sslContext = SSLContexts.custom() .useSSL() .loadKeyMaterial(keystore, keyPassword.toCharArray()) .build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, supportedProtocols, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); return HttpClientBuilder.create() .setDefaultSocketConfig(socketConfig) .setSSLSocketFactory(sf) .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return null; }
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()); } 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()); } SSLContext sslContext = builder.build(); return sslContext; }
/** * @param maxTotal maxTotal * @param maxPerRoute maxPerRoute * @param timeout timeout * @param retryExecutionCount retryExecutionCount * @return */ public static CloseableHttpClient createHttpClient( int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) { try { SSLContext sslContext = SSLContexts.custom().useSSL().build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); poolingHttpClientConnectionManager.setMaxTotal(maxTotal); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig); return HttpClientBuilder.create() .setConnectionManager(poolingHttpClientConnectionManager) .setSSLSocketFactory(sf) .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
public static String wechatPost(String url, String params, InputStream keyStream) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try { keyStore.load(keyStream, WeixinConfig.MCH_ID.toCharArray()); } finally { keyStream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WeixinConfig.MCH_ID.toCharArray()).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(); try { String resp = ""; HttpPost httpPost = new HttpPost(url); StringEntity ent = new StringEntity(params, "utf-8"); ent.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(ent); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { resp += text; } } EntityUtils.consume(entity); return resp; } catch (Exception e) { } finally { response.close(); } } finally { httpclient.close(); } return null; }
private DockerCertificates(final Builder builder) throws DockerCertificateException { if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) { throw new DockerCertificateException( "caCertPath, clientCertPath, and clientKeyPath must all be specified"); } try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())) .readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] {clientCert}); this.sslContext = SSLContexts.custom() .loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD) .useTLS() .build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }
public static HttpClient createHttpClient() { try { SSLContext sslContext = SSLContexts.custom().useSSL().build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClientBuilder.create().setSSLSocketFactory(sf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
protected SSLConnectionSocketFactory getSSLConnectionSocketFactory() { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); SSLContext sslContext = null; try { 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); }
public static HttpClient createHttpClient(int maxTotal, int maxPerRoute) { try { SSLContext sslContext = SSLContexts.custom().useSSL().build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); poolingHttpClientConnectionManager.setMaxTotal(maxTotal); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute); return HttpClientBuilder.create() .setConnectionManager(poolingHttpClientConnectionManager) .setSSLSocketFactory(sf) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
/** * Key store 类型HttpClient * * @param keystore * @param keyPassword * @param supportedProtocols * @param maxTotal * @param maxPerRoute * @return */ public static HttpClient createKeyMaterialHttpClient( KeyStore keystore, String keyPassword, String[] supportedProtocols, int maxTotal, int maxPerRoute) { try { SSLContext sslContext = SSLContexts.custom() .useSSL() .loadKeyMaterial(keystore, keyPassword.toCharArray()) .build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, supportedProtocols, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); poolingHttpClientConnectionManager.setMaxTotal(maxTotal); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute); return HttpClientBuilder.create() .setConnectionManager(poolingHttpClientConnectionManager) .setSSLSocketFactory(sf) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return null; }
/** HttpClient连接SSL */ public void ssl() { CloseableHttpClient httpclient = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore")); try { // 加载keyStore d:\\tomcat.keystore trustStore.load(instream, "123456".toCharArray()); } catch (CertificateException e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } // 相信自己的CA和所有自签名的证书 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // 只允许使用TLSv1协议 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); // 创建http请求(get方式) HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); } } finally { response.close(); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * Returns the HttpClient through which the REST call is made. Uses an unsafe TrustStrategy in * case the user specified a HTTPS URL and set the ignoreUnverifiedSSLPeer flag. * * @param logger the logger to log messages to * @return the HttpClient */ private HttpClient getHttpClient(PrintStream logger) throws Exception { boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String stashServer = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if ("".equals(stashServer) || stashServer == null) { stashServer = descriptor.getStashRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } URL url = new URL(stashServer); HttpClientBuilder builder = HttpClientBuilder.create(); if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, easyStrategy).useTLS().build(); SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } } // Configure the proxy, if needed // Using the Jenkins methods handles the noProxyHost settings ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); builder = builder.setProxy(proxyHost); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); CredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials( new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder .setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } } return builder.build(); }
/** @param args */ public static void main(String[] args) throws Exception { InputStream stream = new FileInputStream("./configCLI.properties"); Properties properties = new Properties(); properties.load(stream); try { stream.close(); } catch (IOException e) { e.printStackTrace(); } downloadURL = (String) properties.get("downloadURL"); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("../etc/keystore")); try { trustStore.load(instream, "storepwd".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.ALLOW_ALL_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); if (args[0].equalsIgnoreCase("-listAll")) { HttpResponse response; try { HttpPost httpPost = new HttpPost(downloadURL); java.util.List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("commandType", "listAll")); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // Make the request response = httpclient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (responseEntity != null) { System.out.println("Response content length: " + responseEntity.getContentLength()); } String jsonResultString = EntityUtils.toString(responseEntity); EntityUtils.consume(responseEntity); System.out.println("----------------------------------------"); System.out.println("result:" + jsonResultString); System.out.println(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } ; } else if (args[0].equalsIgnoreCase("-listCurrent")) { HttpResponse response; try { HttpPost httpPost = new HttpPost(downloadURL); java.util.List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("commandType", "listCurrent")); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // Make the request response = httpclient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (responseEntity != null) { System.out.println("Response content length: " + responseEntity.getContentLength()); } String jsonResultString = EntityUtils.toString(responseEntity); EntityUtils.consume(responseEntity); System.out.println("----------------------------------------"); System.out.println("result:" + jsonResultString); System.out.println(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } else if (args[0].equalsIgnoreCase("-download")) { executeRequest("startDownload", args[1]); } else if (args[0].equalsIgnoreCase("-info")) { executeRequest("getStatus", args[1]); } else if (args[0].equalsIgnoreCase("-pause")) { executeRequest("pause", args[1]); } else if (args[0].equalsIgnoreCase("-resume")) { executeRequest("resume", args[1]); } else if (args[0].equalsIgnoreCase("-remove")) { executeRequest("remove", args[1]); } else if (args[0].equalsIgnoreCase("-changePriority")) { executeRequest("changePriority", args[1]); } else if (args[0].equalsIgnoreCase("-addDAR") || args[0].equalsIgnoreCase("-cancelDAR") || args[0].equalsIgnoreCase("-pauseDAR") || args[0].equalsIgnoreCase("-resumeDAR")) { executeRequest(args[0], args[1]); } else { System.out.println(usage()); } }