@Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); }
private SSLConnectionSocketFactory getSSLConnectionSocketFactory() { // Trust own CA and all self-signed certificates SSLContext sslcontext = null; try { sslcontext = SSLContexts.custom() .loadTrustMaterial(new File("sepa.jks"), "*sepa.jks*".toCharArray(),new TrustSelfSignedStrategy()) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e1) { logger.error(e1.getMessage()); return null; } // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, new SEPAHostnameVerifier()); return sslsf; }
/** * Sets a Safecharge's default {@link LayeredConnectionSocketFactory} object to set connection properties, * such as supported SSL Protocols, hostname verifier, etc(needed to create a https connection). * * @return this object */ public SafechargeClientBuilder setDefaultSSLSocketFactory() { SSLContext sslContext = SSLContexts.createDefault(); String[] javaSupportedProtocols = sslContext.getSupportedSSLParameters() .getProtocols(); List<String> supportedProtocols = new ArrayList<>(); for (String SERVER_SUPPORTED_SSL_PROTOCOL : SERVER_SUPPORTED_SSL_PROTOCOLS) { for (String javaSupportedProtocol : javaSupportedProtocols) { if (SERVER_SUPPORTED_SSL_PROTOCOL.equals(javaSupportedProtocol)) { supportedProtocols.add(SERVER_SUPPORTED_SSL_PROTOCOL); } } } if (!supportedProtocols.isEmpty()) { sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols.toArray(new String[]{}), null, new DefaultHostnameVerifier()); } else { throw new UnsupportedOperationException("Your Java version doesn't support any of the server supported SSL protocols: " + Arrays.toString( SERVER_SUPPORTED_SSL_PROTOCOLS)); } return this; }
@Override public void setSslContextFilePath(String filePath) { if (null == partnerId) { throw new IllegalArgumentException("请设置partnerId的值"); } File file = new File(filePath); if (!file.exists()) { throw new RuntimeException("证书文件:【" + file.getPath() + "】不存在!"); } try { FileInputStream inputStream = new FileInputStream(file); KeyStore keystore = KeyStore.getInstance("PKCS12"); char[] partnerId2charArray = partnerId.toCharArray(); keystore.load(inputStream, partnerId2charArray); this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build(); } catch (Exception e) { throw new RuntimeException("证书文件有问题,请核实!", e); } }
/** * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security, * but may be useful in certain testing or development scenarios. * * @return The SSLContext */ public static SSLContext buildCertificateIgnoringSslContext() { try { return SSLContexts .custom() .loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e); } }
private HttpClient httpClient(JiraConnectionProperties jiraConnectionProperties) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial( jiraConnectionProperties.getSslTrustStore().getFile(), jiraConnectionProperties.getSslTrustStorePassword()) .build(); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(socketFactory, hostnameVerifier); if (jiraConnectionProperties.getSshJumpHost() != null) { sshProxy = new SshProxy(); sslSocketFactory = new SshTunnelSslSocketFactory(sshProxy, sslSocketFactory, jiraConnectionProperties.getSshJumpHost()); } return HttpClientBuilder.create() .setSSLSocketFactory(sslSocketFactory) .build(); } catch (GeneralSecurityException | IOException e) { throw new JiraSyncException("Failed to build custom http client", e); } }
public NestSession(String username, String password) throws LoginException { super(); theLine = null; theBody = null; response = null; theUsername = new String(username); thePassword = new String(password); log.info("Starting Nest login..."); retry = 0; // Trust own CA and all self-signed certs sslcontext = SSLContexts.createDefault(); // Allow TLSv1 protocol only sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); _login(); }
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() { try { SSLContext sslcontext = SSLContexts.custom() //忽略掉对服务器端证书的校验 .loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); return new SSLConnectionSocketFactory( sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { this.log.error(e.getMessage(), e); } return null; }
public static void setupHttpsUnirest() { SSLContext sslcontext = null; try { sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { fail(e.toString()); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); Unirest.setHttpClient(httpclient); }
/** * Creates {@link HttpClient} that trusts any SSL certificate * * @return prepared HTTP client */ protected HttpClient getSSLAcceptingClient() { final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true; try { final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build(); sslContext.init(null, getTrustManager(), new SecureRandom()); final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) { ConsoleUtils.printError(error.getMessage()); throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error); } }
public void setTrustedKeystore(final RestSettings.Keystore keystore) throws Exception { final SSLContextBuilder ssl = SSLContexts.custom(); final String path = keystore.getPath(); final String password = keystore.getPassword(); final URL resource = HttpClientFactoryBean.class.getClassLoader().getResource(path); if (resource == null) { throw new FileNotFoundException(format("Keystore [%s] not found.", path)); } try { ssl.loadTrustMaterial(resource, password == null ? null : password.toCharArray()); builder.setSSLSocketFactory(new SSLConnectionSocketFactory(ssl.build(), getDefaultHostnameVerifier())); } catch (final Exception e) { LOG.error("Error loading keystore [{}]:", path, e); // log full exception, bean initialization code swallows it throw e; } }
@Test @RunAsClient public void hello() throws IOException, GeneralSecurityException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true) .build(); try (CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build()) { String response = Executor.newInstance(httpClient) .execute(Request.Get("https://localhost:8443/")) .returnContent().asString(); assertThat(response).contains("Hello on port 8443, secure: true"); } }
/** * @return */ private HttpClient createSSLHttpClient() { final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException { return true; } }; SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); } catch (final Exception e) { System.out.println("Could not create SSLContext"); } return HttpClientBuilder.create().setSSLContext(sslContext).build(); }
@Test(expected=SSLException.class) public void testSSLTrustVerification() throws Exception { this.server = ServerBootstrap.bootstrap() .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); final HttpContext context = new BasicHttpContext(); // Use default SSL context final SSLContext defaultsslcontext = SSLContexts.createDefault(); final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(defaultsslcontext, NoopHostnameVerifier.INSTANCE); final Socket socket = socketFactory.createSocket(context); final InetSocketAddress remoteAddress = new InetSocketAddress("localhost", this.server.getLocalPort()); final HttpHost target = new HttpHost("localhost", this.server.getLocalPort(), "https"); final SSLSocket sslSocket = (SSLSocket) socketFactory.connectSocket(0, socket, target, remoteAddress, null, context); sslSocket.close(); }
protected static SSLContext createSslCustomContext() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException, NoSuchProviderException { // Load platform specific Trusted CA keystore logger.trace(() -> Arrays.toString(Security.getProviders())); KeyStore tks; switch (AppEnvironment.getInstance().getOsFamily()) { case WINDOWS: tks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI"); tks.load(null, null); break; case OSX: tks = KeyStore.getInstance("KeychainStore", "Apple"); tks.load(null, null); break; case LINUX: case UNSUPPORTED: default: tks = null; break; } return SSLContexts.custom().loadTrustMaterial(tks, null).build(); }
public void initClientSession() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(TRUSTSTORE_FILE, TRUSTSTORE_PASS.toCharArray(), new TrustSelfSignedStrategy()) .loadKeyMaterial(KEYSTORE_FILE, KEYSTORE_PASS.toCharArray(), KEYSTORE_PASS.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); this.httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); }
public void setTrustedKeystore(final Keystore keystore) throws Exception { final SSLContextBuilder ssl = SSLContexts.custom(); final String path = keystore.getPath(); final String password = keystore.getPassword(); final URL resource = HttpClientFactoryBean.class.getClassLoader().getResource(path); if (resource == null) { throw new FileNotFoundException(format("Keystore [%s] not found.", path)); } try { ssl.loadTrustMaterial(resource, password == null ? null : password.toCharArray()); builder.setSSLSocketFactory(new SSLConnectionSocketFactory(ssl.build(), getDefaultHostnameVerifier())); } catch (final Exception e) { LOG.error("Error loading keystore [{}]:", path, e); // log full exception, bean initialization code swallows it throw e; } }
public static HttpClient buildHttpClient(boolean sslEnable, boolean allowSelfSigendCerts, OAuthSigner signer, String host, int port, int socketTimeoutInMillis) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { List<HttpClientConfiguration> configs = new ArrayList<>(); HttpClientConfig httpClientConfig = HttpClientConfig.newBuilder().setSocketTimeoutInMillis(socketTimeoutInMillis).build(); configs.add(httpClientConfig); if (sslEnable) { HttpClientSSLConfig.Builder builder = HttpClientSSLConfig.newBuilder(); builder.setUseSSL(true); if (allowSelfSigendCerts) { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only, use NoopHostnameVerifier to trust self-singed cert builder.setUseSslWithCustomSSLSocketFactory(new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, new NoopHostnameVerifier())); } configs.add(builder.build()); } HttpClientFactory httpClientFactory = new HttpClientFactoryProvider().createHttpClientFactory(configs, false); return httpClientFactory.createClient(signer, host, port); }
private RestTemplate getRestTemplateAllowingSelfSigned() { try { final SSLContext allowSelfSignedSslContext = SSLContexts .custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( allowSelfSignedSslContext, NoopHostnameVerifier.INSTANCE ); final CloseableHttpClient httpClient = HttpClientBuilder .create() .setSSLSocketFactory(sslsf) .build(); return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); } catch (final Exception exception) { throw new SQCompanionException("Can't initialize RestTemplate with Self Signed https support", exception); } }
private void setupSSLclient() { // Handle SSL SSLContext sslcontext = null; SSLConnectionSocketFactory factory = null; try { sslcontext = SSLContexts.custom().useProtocol("SSL").build(); sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom()); factory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); } catch (KeyManagementException | NoSuchAlgorithmException e) { // TODO Auto-generated catch block logError("Could not create SSL context. Entering fail state."); throw new Error(e.getMessage()); } // Create client and context for web stuff. httpclient = HttpClientBuilder.create().setSSLSocketFactory(factory).build(); }
private CloseableHttpClient getHttpClient(@NotNull Integer connectionTimeoutInMilliseconds) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectionTimeoutInMilliseconds) .setConnectionRequestTimeout(connectionTimeoutInMilliseconds) .setSocketTimeout(connectionTimeoutInMilliseconds) .build(); final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); final HttpClientBuilder builder = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setSSLSocketFactory(sslConnectionFactory); return builder.build(); }
public WxSslClient(String certPath, String certPassword) { KeyStore keyStore = null; SSLContext sslcontext = null; try { keyStore = KeyStore.getInstance("PKCS12"); FileInputStream inputStream = new FileInputStream(new File(certPath)); keyStore.load(inputStream, certPassword.toCharArray()); sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build(); } catch (Exception e) { logger.error("initializing WxHttpsClient failed.", e); throw new WxRuntimeException(999, e.getMessage()); } // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();; requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build(); }
public static SSLContext defaultSslContext() { try { URL trustKeyStoreUrl = ConfigProperty.getFileAsUrl("TRUST_JKS_URL", X509Config.class, "/trusted.jks"); char[] trustPassword = ConfigProperty.getPropertyPassword("TRUST_JKS_PWD", "changeit"); URL clientKeyStoreUrl = ConfigProperty.getFileAsUrl("CLIENT_JKS_FILE", X509Config.class, "/test-client.jks"); char[] clientPassword = ConfigProperty.getPropertyPassword("CLIENT_JKS_URL", "changeit"); char[] clientKeyPassword = ConfigProperty.getPropertyPassword("CLIENT_KEY_PWD", clientPassword); SSLContext sslContext = SSLContexts.custom() // Configure trusted certs .loadTrustMaterial(trustKeyStoreUrl, trustPassword) // Configure client certificate .loadKeyMaterial(clientKeyStoreUrl, clientPassword, clientKeyPassword) .build(); return sslContext; } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) { throw new RuntimeException(e); } }
private SSLContext sslContext() { try { 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; }
private SSLContext createSslCustomContext() { try { SSLContextBuilder builder = SSLContexts.custom(); if (options.getKeystore().isPresent()) { KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType()); cks.load(new FileInputStream(options.getKeystore().get().toFile()), options.getKeystorePass().toCharArray()); builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()); } 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()); } if (!options.getKeystore().isPresent() && !options.getKeystore().isPresent()) { return SSLContext.getDefault(); } return builder.build(); } catch (Exception e) { // TODO: DO SOMETHING WITH THE EXCEPTION! LOG.error("Exception", e); } return null; }
protected void init() throws GerbilException { HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder(); try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME); try { keyStore.load(instream, KEY_STORE_PASSWORD); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()) .build(); builder.setSSLContext(sslcontext); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); CloseableHttpClient localClient = builder.build(); this.setClient(localClient); } catch (Exception e) { throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR); } this.setClient(builder.build()); }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { try { SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder.create().setConnectionManager(connectionPool).build(); return HttpClientBuilder.create() .setConnectionManager(connectionPool) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credsProvider).build(); } catch (Exception e) { throw new RuntimeException(e); } }
@Bean public CloseableHttpClient httpClient() { try { //new ClassPathResource("").getURL() SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(keyStore, keyPassword.toCharArray(), new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslcontext, NoopHostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new BeanCreationException("Failed to create http client for ssl connection", e); } }
public static Client createClient(String serverCert, String clientCert, String clientKey, boolean debug, Class debugClass) throws Exception { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(KeyStoreUtil.createTrustStore(serverCert), null) .loadKeyMaterial(KeyStoreUtil.createKeyStore(clientCert, clientKey), "consul".toCharArray()) .build(); ClientConfig config = new ClientConfig(); config.property(ClientProperties.FOLLOW_REDIRECTS, "false"); config.property(ClientProperties.CONNECT_TIMEOUT, CONNECT_TIMEOUT_MS); config.register(MultiPartFeature.class); ClientBuilder builder = ClientBuilder.newBuilder().withConfig(config); builder.sslContext(sslContext); builder.hostnameVerifier(CertificateTrustManager.hostnameVerifier()); if (debug) { builder = builder.register(new LoggingFilter(java.util.logging.Logger.getLogger(debugClass.getName()), true)); } Client client = builder.build(); LOGGER.debug("Jax rs client has been constructed: {}, sslContext: {}", client, sslContext); return client; }
private Executor executor() { if (executor == null) { if (this.host.startsWith("https://")) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, (chain, authType) -> true) .build(); builder.setSSLContext(sslContext); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); } catch (Exception ex) { Throwables.propagate(ex); } } client = builder.build(); executor = Executor.newInstance(client); if (creds != null) { executor.auth(creds); } } return executor; }
/** * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution * as it undermines security, but may be useful in certain testing or development * scenarios. * * @return an SSLContext that will ignore peer certificates */ public static SSLContext buildCertificateIgnoringSslContext() { try { return SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new IllegalStateException( "Unexpected exception while building the certificate-ignoring SSLContext" + ".", e); } }
/** * Gets the trusted ssl context. * * @param trustStoreFile the trust store file * @param trustStorePassword the trust store password * @param trustStoreType the trust store type * @return the trusted ssl context */ private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword, final String trustStoreType) { try { final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType); final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray(); try (InputStream casStream = trustStoreFile.getInputStream()) { casTrustStore.load(casStream, trustStorePasswordCharArray); } final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray); final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null); final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore); final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null); final KeyManager[] keyManagers = { new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager)) }; final TrustManager[] trustManagers = { new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager)) }; final SSLContext context = SSLContexts.custom().useProtocol("SSL").build(); context.init(keyManagers, trustManagers, null); return context; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw Throwables.propagate(e); } }
@ConditionalOnMissingBean(name = "trustStoreSslSocketFactory") @Bean public SSLConnectionSocketFactory trustStoreSslSocketFactory() { final HttpClientProperties.Truststore client = casProperties.getHttpClient().getTruststore(); if (client.getFile() != null && client.getFile().exists() && StringUtils.isNotBlank(client.getPsw())) { return new FileTrustStoreSslSocketFactory(client.getFile(), client.getPsw()); } return new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()); }
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException { RestClientBuilder builder = RestClient.builder(hosts); String keystorePath = settings.get(TRUSTSTORE_PATH); if (keystorePath != null) { final String keystorePass = settings.get(TRUSTSTORE_PASSWORD); if (keystorePass == null) { throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD); } Path path = PathUtils.get(keystorePath); if (!Files.exists(path)) { throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file"); } try { KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream is = Files.newInputStream(path)) { keyStore.load(is, keystorePass.toCharArray()); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build(); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext); builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy)); } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) { throw new RuntimeException("Error setting up ssl", e); } } try (ThreadContext threadContext = new ThreadContext(settings)) { Header[] defaultHeaders = new Header[threadContext.getHeaders().size()]; int i = 0; for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) { defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue()); } builder.setDefaultHeaders(defaultHeaders); } return builder.build(); }
public static CloseableHttpAsyncClient createSSLClient(HttpHost proxy) { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }; try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); HttpAsyncClientBuilder client = HttpAsyncClients.custom() .setDefaultCookieStore(new BasicCookieStore()) .setSSLContext(sslContext) .setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); if (proxy !=null) { client.setProxy(proxy); } return client.build(); } catch (Exception e) { System.out.println("Could not create SSLContext"); return null; } }
/** * 创建httpclient连接池,并初始化httpclient */ public void init() { try { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); // Increase max total connection to 200 httpClientConnectionManager.setMaxTotal(maxTotalPool); // Increase default max connection per route to 20 httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build(); httpClientConnectionManager.setDefaultSocketConfig(socketConfig); } catch (Exception e) { } }
@Bean("httpClient") @Profile("insecure") @SneakyThrows public HttpClient insecureHttpClient(@Value("${spring.application.name}") String userAgent) { // http://stackoverflow.com/a/41618092/1393467 TrustStrategy trustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).build(); return configure(HttpClients.custom(), userAgent) .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) .build(); }
private static CloseableHttpClient getCloseableHttpClient() { SSLContext sslcontext = SSLContexts.createDefault(); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[]{HttpConstant.TLS_VERSION}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(factory).build(); }
static Registry<ConnectionSocketFactory> getDefaultRegistry() { return RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(), new String[] { "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello", }, null, new NoopHostnameVerifier())) .build(); }
private SSLConnectionSocketFactory initSslContext(String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword, String trustStoreType, String trustStorePath, String trustStorePassword) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, KeyManagementException { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (StringUtils.isNoneBlank(keyStorePath)) { KeyStore keyStore = SslUtils.getStore(keyStoreType, keyStorePath, keyStorePassword); if (keyStore.size() == 0) { throw new IllegalStateException("Key store has no keys"); } sslContextBuilder.loadKeyMaterial(keyStore, keyPassword.toCharArray()); } if (StringUtils.isNoneBlank(trustStorePath)) { KeyStore trustStore = SslUtils.getStore(trustStoreType, trustStorePath, trustStorePassword); if (trustStore.size() == 0) { throw new IllegalStateException("Trust store has no keys"); } sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } return new SSLConnectionSocketFactory( sslContextBuilder.build(), SSLConnectionSocketFactory.getDefaultHostnameVerifier()); }