Search in sources :

Example 1 with TrustStrategy

use of org.apache.hc.core5.ssl.TrustStrategy in project mercury by yellow013.

the class AsyncClientCustomSSL method main.

public static void main(final String[] args) throws Exception {
    // Trust standard CA and those trusted by our custom strategy
    final SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            final X509Certificate cert = chain[0];
            return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
        }
    }).build();
    final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create().setSslContext(sslcontext).build();
    final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(tlsStrategy).build();
    try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build()) {
        client.start();
        final HttpHost target = new HttpHost("https", "httpbin.org");
        final HttpClientContext clientContext = HttpClientContext.create();
        final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
        System.out.println("Executing request " + request);
        final Future<SimpleHttpResponse> future = client.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), clientContext, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(final SimpleHttpResponse response) {
                System.out.println(request + "->" + new StatusLine(response));
                final SSLSession sslSession = clientContext.getSSLSession();
                if (sslSession != null) {
                    System.out.println("SSL protocol " + sslSession.getProtocol());
                    System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
                }
                System.out.println(response.getBody());
            }

            @Override
            public void failed(final Exception ex) {
                System.out.println(request + "->" + ex);
            }

            @Override
            public void cancelled() {
                System.out.println(request + " cancelled");
            }
        });
        future.get();
        System.out.println("Shutting down");
        client.close(CloseMode.GRACEFUL);
    }
}
Also used : TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) TrustStrategy(org.apache.hc.core5.ssl.TrustStrategy) SSLSession(javax.net.ssl.SSLSession) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) CertificateException(java.security.cert.CertificateException) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)

Example 2 with TrustStrategy

use of org.apache.hc.core5.ssl.TrustStrategy in project httpcomponents-core by apache.

the class TestSSLContextBuilder method testSSLHandshakeServerCustomTrustStrategy.

@Test
public void testSSLHandshakeServerCustomTrustStrategy() throws Exception {
    final URL resource1 = getResource("/test-server.p12");
    final String storePassword = "nopassword";
    final String keyPassword = "nopassword";
    final SSLContext serverSslContext = SSLContextBuilder.create().loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()).build();
    Assertions.assertNotNull(serverSslContext);
    final AtomicReference<X509Certificate[]> certChainRef = new AtomicReference<>();
    final TrustStrategy trustStrategy = (chain, authType) -> {
        certChainRef.set(chain);
        return true;
    };
    final SSLContext clientSslContext = SSLContextBuilder.create().loadTrustMaterial(trustStrategy).build();
    Assertions.assertNotNull(clientSslContext);
    final ServerSocket serverSocket = serverSslContext.getServerSocketFactory().createServerSocket();
    serverSocket.bind(new InetSocketAddress(0));
    this.executorService = Executors.newSingleThreadExecutor();
    final Future<Boolean> future = this.executorService.submit(() -> {
        try (Socket socket = serverSocket.accept()) {
            final OutputStream outputStream = socket.getOutputStream();
            outputStream.write(new byte[] { 'H', 'i' });
            outputStream.flush();
        }
        return Boolean.TRUE;
    });
    final int localPort = serverSocket.getLocalPort();
    try (final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket()) {
        clientSocket.connect(new InetSocketAddress("localhost", localPort), TIMEOUT.toMillisecondsIntBound());
        clientSocket.setSoTimeout(TIMEOUT.toMillisecondsIntBound());
        final InputStream inputStream = clientSocket.getInputStream();
        Assertions.assertEquals('H', inputStream.read());
        Assertions.assertEquals('i', inputStream.read());
        Assertions.assertEquals(-1, inputStream.read());
    }
    final Boolean result = future.get(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result);
    final X509Certificate[] certs = certChainRef.get();
    Assertions.assertNotNull(certs);
    Assertions.assertEquals(2, certs.length);
    final X509Certificate cert1 = certs[0];
    final Principal subjectDN1 = cert1.getSubjectDN();
    Assertions.assertNotNull(subjectDN1);
    Assertions.assertEquals("CN=Test Server, OU=HttpComponents Project, O=Apache Software Foundation", subjectDN1.getName());
    final X509Certificate cert2 = certs[1];
    final Principal subjectDN2 = cert2.getSubjectDN();
    Assertions.assertNotNull(subjectDN2);
    Assertions.assertEquals("EMAILADDRESS=dev@hc.apache.org, " + "CN=Test CA, OU=HttpComponents Project, O=Apache Software Foundation", subjectDN2.getName());
    final Principal issuerDN = cert2.getIssuerDN();
    Assertions.assertNotNull(issuerDN);
    Assertions.assertEquals("EMAILADDRESS=dev@hc.apache.org, " + "CN=Test CA, OU=HttpComponents Project, O=Apache Software Foundation", issuerDN.getName());
}
Also used : X509Certificate(java.security.cert.X509Certificate) Socket(java.net.Socket) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) SSLSocket(javax.net.ssl.SSLSocket) Security(java.security.Security) KeyStoreException(java.security.KeyStoreException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerSocket(java.net.ServerSocket) Future(java.util.concurrent.Future) SSLSession(javax.net.ssl.SSLSession) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LinkedHashSet(java.util.LinkedHashSet) ExecutorService(java.util.concurrent.ExecutorService) OutputStream(java.io.OutputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Set(java.util.Set) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) KeyStore(java.security.KeyStore) InetSocketAddress(java.net.InetSocketAddress) Timeout(org.apache.hc.core5.util.Timeout) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) SSLException(javax.net.ssl.SSLException) AfterEach(org.junit.jupiter.api.AfterEach) Principal(java.security.Principal) SSLServerSocket(javax.net.ssl.SSLServerSocket) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Assertions(org.junit.jupiter.api.Assertions) NoSuchProviderException(java.security.NoSuchProviderException) InputStream(java.io.InputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) SSLSocket(javax.net.ssl.SSLSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) Principal(java.security.Principal) Test(org.junit.jupiter.api.Test)

Example 3 with TrustStrategy

use of org.apache.hc.core5.ssl.TrustStrategy in project mercury by yellow013.

the class ClientCustomSSL method main.

public static final void main(final String[] args) throws Exception {
    // Trust standard CA and those trusted by our custom strategy
    final SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            final X509Certificate cert = chain[0];
            return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
        }
    }).build();
    // Allow TLSv1.2 protocol only
    final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(sslcontext).setTlsVersions(TLS.V_1_2).build();
    final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
    try (CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build()) {
        final HttpGet httpget = new HttpGet("https://httpbin.org/");
        System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
        final HttpClientContext clientContext = HttpClientContext.create();
        try (CloseableHttpResponse response = httpclient.execute(httpget, clientContext)) {
            System.out.println("----------------------------------------");
            System.out.println(response.getCode() + " " + response.getReasonPhrase());
            System.out.println(EntityUtils.toString(response.getEntity()));
            final SSLSession sslSession = clientContext.getSSLSession();
            if (sslSession != null) {
                System.out.println("SSL protocol " + sslSession.getProtocol());
                System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
            }
        }
    }
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) TrustStrategy(org.apache.hc.core5.ssl.TrustStrategy) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) SSLSession(javax.net.ssl.SSLSession) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SSLContext(javax.net.ssl.SSLContext) HttpClientConnectionManager(org.apache.hc.client5.http.io.HttpClientConnectionManager) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate)

Example 4 with TrustStrategy

use of org.apache.hc.core5.ssl.TrustStrategy in project commercetools-jvm-sdk by commercetools.

the class IntegrationTest method createNoSSLClient.

private static CloseableHttpAsyncClient createNoSSLClient() {
    final TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    try {
        final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        Lookup<TlsStrategy> socketFactoryRegistry = RegistryBuilder.<TlsStrategy>create().register("https", new DefaultClientTlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE)).build();
        PoolingAsyncClientConnectionManager connManager = new PoolingAsyncClientConnectionManager(socketFactoryRegistry);
        return HttpAsyncClients.createMinimal(connManager);
    } catch (Exception e) {
        logger.error("Could not create SSLContext", e);
        return null;
    }
}
Also used : TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) DefaultClientTlsStrategy(org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy) DefaultClientTlsStrategy(org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy) TrustStrategy(org.apache.hc.core5.ssl.TrustStrategy) SSLContext(javax.net.ssl.SSLContext) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException)

Aggregations

X509Certificate (java.security.cert.X509Certificate)4 SSLContext (javax.net.ssl.SSLContext)4 SSLSession (javax.net.ssl.SSLSession)3 TrustStrategy (org.apache.hc.core5.ssl.TrustStrategy)3 IOException (java.io.IOException)2 PoolingAsyncClientConnectionManager (org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)2 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 UncheckedIOException (java.io.UncheckedIOException)1 InetSocketAddress (java.net.InetSocketAddress)1 ServerSocket (java.net.ServerSocket)1 Socket (java.net.Socket)1 URL (java.net.URL)1 KeyStore (java.security.KeyStore)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1 Principal (java.security.Principal)1 Security (java.security.Security)1