类org.apache.http.conn.ssl.DefaultHostnameVerifier源码实例Demo

下面列出了怎么用org.apache.http.conn.ssl.DefaultHostnameVerifier的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: mutual-tls-ssl   文件: SSLFactoryTestHelper.java
public static SSLFactory createSSLFactory(boolean oneWayAuthenticationEnabled, boolean twoWayAuthenticationEnabled) {
    String keyStorePath = "keystores-for-unit-tests/identity.jks";
    String keyStorePassword = "secret";
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder();
    if (oneWayAuthenticationEnabled) {
        sslFactoryBuilder.withTrustMaterial(trustStorePath, trustStorePassword.toCharArray())
                .withHostnameVerifier(new DefaultHostnameVerifier());
    }

    if (twoWayAuthenticationEnabled) {
        sslFactoryBuilder.withIdentityMaterial(keyStorePath, keyStorePassword.toCharArray())
                .withTrustMaterial(trustStorePath, trustStorePassword.toCharArray())
                .withHostnameVerifier(new DefaultHostnameVerifier());
    }
    return Mockito.spy(sslFactoryBuilder.build());
}
 
源代码2 项目: mutual-tls-ssl   文件: ClientConfigShould.java
@Test
public void createSslFactoryWithTwoWayAuthentication() {
    String keyStorePath = "keystores-for-unit-tests/identity.jks";
    String keyStorePassword = "secret";
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory sslFactory = victim.sslFactory(false, true,
            keyStorePath, keyStorePassword.toCharArray(), trustStorePath, trustStorePassword.toCharArray());

    assertThat(sslFactory).isNotNull();
    assertThat(sslFactory.getSslContext()).isNotNull();
    assertThat(sslFactory.getKeyManager()).isPresent();
    assertThat(sslFactory.getTrustManager()).isNotNull();
    assertThat(sslFactory.getHostnameVerifier()).isInstanceOf(DefaultHostnameVerifier.class);
    assertThat(sslFactory.getSslContext().getProtocol()).isEqualTo("TLSv1.3");
}
 
源代码3 项目: api-layer   文件: SecurityUtils.java
public static SSLConfig getConfiguredSslConfig() {
    TlsConfiguration tlsConfiguration = ConfigReader.environmentConfiguration().getTlsConfiguration();
    try {
        SSLContext sslContext = SSLContexts.custom()
            .loadKeyMaterial(
                new File(tlsConfiguration.getKeyStore()),
                tlsConfiguration.getKeyStorePassword() != null ? tlsConfiguration.getKeyStorePassword().toCharArray() : null,
                tlsConfiguration.getKeyPassword() != null ? tlsConfiguration.getKeyPassword().toCharArray() : null,
                (aliases, socket) -> tlsConfiguration.getKeyAlias())
            .loadTrustMaterial(
                new File(tlsConfiguration.getTrustStore()),
                tlsConfiguration.getTrustStorePassword() != null ? tlsConfiguration.getTrustStorePassword().toCharArray() : null)
            .build();
        SSLSocketFactoryAdapter sslSocketFactory = new SSLSocketFactoryAdapter(new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier()));
        return SSLConfig.sslConfig().with().sslSocketFactory(sslSocketFactory);
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
        | CertificateException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
 
源代码5 项目: lucene-solr   文件: HttpClientUtilTest.java
@Test
// commented out on: 24-Dec-2018   @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018
public void testSSLSystemProperties() throws IOException {

  assertNotNull("HTTPS scheme could not be created using system defaults",
                HttpClientUtil.getSocketFactoryRegistryProvider().getSocketFactoryRegistry().lookup("https"));

  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());

  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "true");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());

  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());
  
  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "false");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(NoopHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());
}
 
源代码6 项目: vespa   文件: SimpleHttpClient.java
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
                        int listenPort, boolean useCompression) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (!useCompression) {
        builder.disableContentCompression();
    }
    if (sslContext != null) {
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext,
                toArray(enabledProtocols),
                toArray(enabledCiphers),
                new DefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslConnectionFactory);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .build();
        builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        scheme = "https";
    } else {
        scheme = "http";
    }
    this.delegate = builder.build();
    this.listenPort = listenPort;
}
 
源代码7 项目: navigator-sdk   文件: SSLUtilsTest.java
@Test
public void testGetHostnameVerifier() {
  // Default
  HostnameVerifier verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof DefaultHostnameVerifier);

  // Override
  config.setOverrideHostnameVerifier(new TestHostnameVerifier());
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof TestHostnameVerifier);

  // Disabled
  config.setDisableSSLValidation(true);
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof NoopHostnameVerifier);
}
 
private HostnameVerifier getHostnameVerifier() {
    if (isHostnameVerificationEnabled()) {
        return new DefaultHostnameVerifier();
    } else {
        return NoopHostnameVerifier.INSTANCE;
    }
}
 
源代码9 项目: cellery-security   文件: CelleryCellStsService.java
private void setHttpClientProperties() throws CelleryCellSTSException {

        CelleryTrustManager celleryTrustManager = new CelleryTrustManager();
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{celleryTrustManager}, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(
                    new CelleryHostnameVerifier(new DefaultHostnameVerifier()));
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new CelleryCellSTSException("Error while initializing SSL context");
        }

    }
 
private void initSSLContext(HttpClientBuilder httpClientBuilder) throws WxPayException {
  SSLContext sslContext = this.getConfig().getSslContext();
  if (null == sslContext) {
    sslContext = this.getConfig().initSSLContext();
  }

  SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
    new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
  httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
}
 
源代码11 项目: mutual-tls-ssl   文件: ClientConfig.java
@Bean
@Scope("prototype")
public SSLFactory sslFactory(
        @Value("${client.ssl.one-way-authentication-enabled:false}") boolean oneWayAuthenticationEnabled,
        @Value("${client.ssl.two-way-authentication-enabled:false}") boolean twoWayAuthenticationEnabled,
        @Value("${client.ssl.key-store:}") String keyStorePath,
        @Value("${client.ssl.key-store-password:}") char[] keyStorePassword,
        @Value("${client.ssl.trust-store:}") String trustStorePath,
        @Value("${client.ssl.trust-store-password:}") char[] trustStorePassword) {
    if (!oneWayAuthenticationEnabled && !twoWayAuthenticationEnabled) {
        return null;
    }

    SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder()
            .withHostnameVerifier(new DefaultHostnameVerifier())
            .withProtocol("TLSv1.3");

    if (oneWayAuthenticationEnabled) {
        sslFactoryBuilder.withTrustMaterial(trustStorePath, trustStorePassword);
    }

    if (twoWayAuthenticationEnabled) {
        sslFactoryBuilder.withIdentityMaterial(keyStorePath, keyStorePassword)
                .withTrustMaterial(trustStorePath, trustStorePassword);
    }
    return sslFactoryBuilder.build();
}
 
源代码12 项目: mutual-tls-ssl   文件: ClientConfigShould.java
@Test
public void createSslFactoryWithOneWayAuthentication() {
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory sslFactory = victim.sslFactory(true, false,
            EMPTY, EMPTY.toCharArray(), trustStorePath, trustStorePassword.toCharArray());

    assertThat(sslFactory).isNotNull();
    assertThat(sslFactory.getSslContext()).isNotNull();
    assertThat(sslFactory.getKeyManager()).isNotPresent();
    assertThat(sslFactory.getTrustManager()).isNotNull();
    assertThat(sslFactory.getHostnameVerifier()).isInstanceOf(DefaultHostnameVerifier.class);
    assertThat(sslFactory.getSslContext().getProtocol()).isEqualTo("TLSv1.3");
}
 
private HtmlUnitSSLConnectionSocketFactory(final KeyStore keystore, final char[] keystorePassword,
        final KeyStore truststore, final boolean useInsecureSSL,
        final String[] supportedProtocols, final String[] supportedCipherSuites)
    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(SSLContexts.custom()
            .loadKeyMaterial(keystore, keystorePassword).loadTrustMaterial(truststore, null).build(),
            supportedProtocols, supportedCipherSuites,
            new DefaultHostnameVerifier());
    useInsecureSSL_ = useInsecureSSL;
}
 
源代码14 项目: emissary   文件: HTTPConnectionFactory.java
@VisibleForTesting
HTTPConnectionFactory(final Configurator config) {
    Registry<ConnectionSocketFactory> registry = null;
    try {
        final Configurator cfg = config == null ? ConfigUtil.getConfigInfo(HTTPConnectionFactory.class) : config;
        // if someone doesn't want keep alives...
        if (!cfg.findBooleanEntry(CFG_HTTP_KEEPALIVE, DFLT_KEEPALIVE)) {
            this.connReuseStrategy = NoConnectionReuseStrategy.INSTANCE;
        }
        this.maxConns = cfg.findIntEntry(CFG_HTTP_MAXCONNS, DFLT_MAXCONNS);
        this.userAgent = cfg.findStringEntry(CFG_HTTP_AGENT, DEFAULT_HTTP_AGENT);
        final SSLContext sslContext = build(cfg);
        // mainly for using in test environments where cert name may not match host name
        final HostnameVerifier v = cfg.findBooleanEntry(CFG_NOOP_VERIFIER, false) ? new NoopHostnameVerifier() : new DefaultHostnameVerifier();
        registry =
                RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, PlainConnectionSocketFactory.getSocketFactory())
                        .register(HTTPS, new SSLConnectionSocketFactory(sslContext, v)).build();
    } catch (IOException | GeneralSecurityException ex) {
        log.error("Error configuring HTTPConnectionFactory. The connection factory will use HTTP Client default settings", ex);
    }
    if (registry == null) {
        this.connMan = new PoolingHttpClientConnectionManager();
    } else {
        this.connMan = new PoolingHttpClientConnectionManager(registry);
    }

    this.connMan.setMaxTotal(this.maxConns);
}
 
源代码15 项目: DataflowTemplates   文件: HttpEventPublisher.java
/**
 * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
 * HEC.
 *
 * @param maxConnections max number of parallel connections.
 * @param disableCertificateValidation should disable certificate validation.
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
源代码16 项目: api-layer   文件: HttpsFactoryTest.java
@Test
public void shouldCreateDefaultHostnameVerifier() {
    HttpsConfig httpsConfig = httpsConfigBuilder.build();
    HttpsFactory httpsFactory = new HttpsFactory(httpsConfig);
    HostnameVerifier hostnameVerifier = httpsFactory.createHostnameVerifier();
    assertEquals(DefaultHostnameVerifier.class, hostnameVerifier.getClass());
}
 
源代码17 项目: qonduit   文件: HttpClient.java
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
 
源代码18 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
private Registry<ConnectionSocketFactory> createConnectionSocketFactory() {
  HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault());
  ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextOverride != null ?
      sslContextOverride : defaultSslContext, sslSupportedProtocols, null, hostnameVerifier);

  return RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslSocketFactory)
      .build();
}
 
源代码19 项目: beam   文件: HttpEventPublisher.java
/**
 * Creates a {@link CloseableHttpClient} to make HTTP POSTs against Splunk's HEC.
 *
 * @param maxConnections max number of parallel connections
 * @param disableCertificateValidation should disable certificate validation
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
/**
 * This test verifies {@link DefaultHostnameVerifier} behavior and gives fair idea about host matching result
 *
 * @throws Exception
 */
@Test
public void testDefaultHostVerifier() throws Exception {
    log.info("-- Starting {} test --", methodName);
    Method matchIdentityStrict = DefaultHostnameVerifier.class.getDeclaredMethod("matchIdentityStrict",
            String.class, String.class, PublicSuffixMatcher.class);
    matchIdentityStrict.setAccessible(true);
    Assert.assertTrue((boolean) matchIdentityStrict.invoke(null, "pulsar", "pulsar", null));
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar.com", "pulsar", null));
    Assert.assertTrue((boolean) matchIdentityStrict.invoke(null, "pulsar-broker1.com", "pulsar*.com", null));
    // unmatched remainder: "1-broker." should not contain "."
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar-broker1.com", "pulsar*com", null));
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar.com", "*", null));
    log.info("-- Exiting {} test --", methodName);
}
 
源代码21 项目: pulsar   文件: DirectProxyHandler.java
private boolean verifyTlsHostName(String hostname, ChannelHandlerContext ctx) {
    ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");

    SSLSession sslSession = null;
    if (sslHandler != null) {
        sslSession = ((SslHandler) sslHandler).engine().getSession();
        return (new DefaultHostnameVerifier()).verify(hostname, sslSession);
    }
    return false;
}
 
源代码22 项目: navigator-sdk   文件: SSLUtils.java
/**
 * If SSL validation is disabled then return a HostnameVerifier that accepts
 * everything. Otherwise, return the override HostnameVerifier in the config
 * if specified, or return a new DefaultHostnameVerifier
 *
 * @param config
 */
public static HostnameVerifier getHostnameVerifier(ClientConfig config) {
  if (config.isDisableSSLValidation()) {
    return new NoopHostnameVerifier();
  }
  if (config.getOverrideHostnameVerifier() == null) {
    return new DefaultHostnameVerifier();
  } else {
    return config.getOverrideHostnameVerifier();
  }
}
 
源代码23 项目: helios   文件: DefaultHttpConnector.java
public DefaultHttpConnector(final EndpointIterator endpointIterator,
                            final int httpTimeoutMillis,
                            final boolean sslHostnameVerificationEnabled) {
  this.endpointIterator = endpointIterator;
  this.httpTimeoutMillis = httpTimeoutMillis;
  this.hostnameVerifierProvider =
      new HostnameVerifierProvider(sslHostnameVerificationEnabled, new DefaultHostnameVerifier());
  this.extraHttpsHandler = null;
}
 
源代码24 项目: commons-vfs   文件: Http4FileProvider.java
private HostnameVerifier createHostnameVerifier(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    if (!builder.isHostnameVerificationEnabled(fileSystemOptions)) {
        return NoopHostnameVerifier.INSTANCE;
    }

    return new DefaultHostnameVerifier();
}
 
源代码25 项目: apiman   文件: DefaultEsClientFactory.java
/**
 * Configures the SSL connection to use certificates by setting the keystores
 * @param httpConfig the http client configuration
 * @param config the configuration
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client.keystore");
        String clientKeystorePassword = config.get("client.keystore.password");
        String trustStorePath = config.get("client.truststore");
        String trustStorePassword = config.get("client.truststore.password");

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

        String trustCertificate = config.get("client.trust.certificate");
        if (!StringUtils.isBlank(trustCertificate) && trustCertificate.equals("true")) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
        }

        SSLContext sslContext = sslContextBuilder.build();
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), new SecureRandom());

        String trustHost = config.get("client.trust.host");
        HostnameVerifier hostnameVerifier = !StringUtils.isBlank(trustHost) && trustHost.equals("true") ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}
 
CloseableHttpClient getHttpClient()  {

        // TODO: set a timeout until we have a proper way to deal with back pressure
        int timeout = 5;

        RequestConfig config = RequestConfig.custom()
          .setConnectTimeout(timeout * 1000)
          .setConnectionRequestTimeout(timeout * 1000)
          .setSocketTimeout(timeout * 1000).build();

        final TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) {
                return true;
            }
        };

	    try {

	        if(!verifySSL) {
	            return HttpClients.custom()
	                    .setSSLSocketFactory(
	                            new SSLConnectionSocketFactory(
	                                    new SSLContextBuilder()
	                                    .loadTrustMaterial(trustAllStrategy)
	                                    .build(),
	                                    NoopHostnameVerifier.INSTANCE))
	                    .setDefaultRequestConfig(config)
	                    .build();
	        }

	        if(effectiveTruststore == null) {
	            return HttpClients.custom()
                        .setDefaultRequestConfig(config)
                        .build();
	        }

		    return HttpClients.custom()
		            .setSSLSocketFactory(
		                    new SSLConnectionSocketFactory(
		                            new SSLContextBuilder()
		                            .loadTrustMaterial(effectiveTruststore, null)
		                            .build(),
		                            new DefaultHostnameVerifier()))
		            .setDefaultRequestConfig(config)
		            .build();


	    } catch(Exception ex) {
	    	log.error("Could not create HTTPClient due to {}, audit log not available.", ex.getMessage(), ex);
	    	return null;
	    }
	}
 
源代码28 项目: substitution-schedule-parser   文件: BaseParser.java
public CustomHostnameVerifier(String host) {
    this.host = host;
    this.defaultHostnameVerifier = new DefaultHostnameVerifier();
}
 
/**
 * Creates a new SSLConnectionSocketFactory with the behavior described in
 * {@link #getFactory(String, CodeDxExtension)}. Instead of returning, this
 * method registers the factory instance to the <code>factoriesByHost<code>
 * map, as well as registering its <code>ExtraCertManager</code> to the
 * <code>certManagersByHost</code> map. The cert manager registration is
 * important in order to detect and purge trusted certificates on a per-host
 * basis.
 * 
 * @param host
 * @param extension
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static void initializeFactory(
	String host,
	CodeDxExtension extension,
	String fingerprint,
	boolean acceptPermanently
) throws IOException, GeneralSecurityException {
	// set up the certificate management
	File managedKeyStoreFile = getTrustStoreForHost(host);
	ExtraCertManager certManager = new SingleExtraCertManager(managedKeyStoreFile, "u9lwIfUpaN");

	// get the default hostname verifier that gets used by the modified one
	// and the invalid cert dialog
	HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();

	
	InvalidCertificateStrategy invalidCertStrat;
	if(fingerprint == null){
		invalidCertStrat = new InvalidCertificateDialogStrategy(defaultHostnameVerifier, host, extension);
	} else {
		invalidCertStrat = new InvalidCertificateFingerprintStrategy(fingerprint, acceptPermanently);
	}

	/*
	 * Set up a composite trust manager that uses the default trust manager
	 * before delegating to the "reloadable" trust manager that allows users
	 * to accept invalid certificates.
	 */
	List<X509TrustManager> trustManagersForComposite = new LinkedList<>();
	X509TrustManager systemTrustManager = getDefaultTrustManager();
	ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, invalidCertStrat);
	trustManagersForComposite.add(systemTrustManager);
	trustManagersForComposite.add(customTrustManager);
	X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);

	// setup the SSLContext using the custom trust manager
	SSLContext sslContext = SSLContext.getInstance("TLS");
	sslContext.init(null, new TrustManager[] { trustManager }, null);
	// the actual hostname verifier that will be used with the socket
	// factory
	Set<String> allowedHosts = new HashSet<>();
	allowedHosts.add(host);
	HostnameVerifier modifiedHostnameVerifier = new HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts);
	
	SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier);
	// Register the `factory` and the `customTrustManager` under the given
	// `host`
	if(fingerprint == null){
		dialogFactoriesByHost.put(host, factory);
	} else {
		fingerprintFactoriesByHost.put(host, factory);
	}
}
 
源代码30 项目: nifi   文件: WebUtils.java
/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration
 * @param ctx    security context, which may be null for non-secure client
 *               creation
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {

    ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    if (config != null) {
        clientBuilder = clientBuilder.withConfig(config);
    }

    if (ctx != null) {

        // Apache http DefaultHostnameVerifier that checks subject alternative names against the hostname of the URI
        clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(new DefaultHostnameVerifier());
    }

    clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class);

    return clientBuilder.build();

}
 
 类所在包
 类方法
 同包方法