当前位置: 首页 > 面试题库 >

与jdk8加密以为http2启用ALPN

邹时铭
2023-03-14
问题内容

我一直在搜索如何使用 conscrypt-openjdk-uber-1.4.1.jar* for jdk8 来实现 Conscrypt
SSL提供程序,以支持 ALPN 与服务器建立 http2(使用apache httpclient 5) 连接,因为
jdk8默认不支持ALPN 或另一种解决方案是迁移到jdk9(或更高版本),目前尚不可行,因为我们的产品 严重依赖于jdk8

*

我一直在广泛搜索一些要实施的文档或示例,但找不到。

我尝试将conscrypt提供程序作为默认提供程序插入,我的程序将其用作默认提供程序,但仍然无法与http2服务器连接,我的示例如下,

public static void main(final String[] args) throws Exception {
    Security.insertProviderAt(new OpenSSLProvider(), 1);
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
    final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE)).build();
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, null, ioReactorConfig, connectionManager);

    client.start();
    final HttpHost target = new HttpHost("localhost", 8082, "https");
    final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
    final AsyncClientEndpoint endpoint = leaseFuture.get(10, TimeUnit.SECONDS);
    try {
        String[] requestUris = new String[] {"/"};
        CountDownLatch latch = new CountDownLatch(requestUris.length);
        for (final String requestUri: requestUris) {
            SimpleHttpRequest request = SimpleHttpRequest.get(target, requestUri);
            endpoint.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() {
                        @Override
                        public void completed(final SimpleHttpResponse response) {
                            latch.countDown();
                            System.out.println(requestUri + "->" + response.getCode());
                            System.out.println(response.getBody());
                        }

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

                        @Override
                        public void cancelled() {
                            latch.countDown();
                            System.out.println(requestUri + " cancelled");
                        }

                    });
        }
        latch.await();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        endpoint.releaseAndReuse();
    }

    client.shutdown(ShutdownType.GRACEFUL);
}

这个程序给出的输出为

org.apache.hc.core5.http.ConnectionClosedException:连接已关闭org.apache.hc.core5.http.ConnectionClosedException:连接已在org.apache.hc.core5.http2.impl.nio.FrameInputBuffer.read(FrameInputBuffer.java
:146),位于org.apache.hc.core5.http2.impl.nio.AbstractHttp2StreamMultiplexer.onInput(AbstractHttp2StreamMultiplexer.java:415),位于org.apache.hc.core5.http2.impl.nio.AbstractHttp2IOEventHandler.inputReady(AbstractHttp2IOEventHandler.java
:63),位于org.apache.hc.core5.reactor.InternalDataChannel.onIOEvent(InternalDataChannel.java:117),位于org.apache.hc.core5.http2.impl.nio.ClientHttp2IOEventHandler.inputReady(ClientHttp2IOEventHandler.java:38)
org.apache.hc.core5.reactor.SingleCoreIOReactor上的org.apache.hc.core5.reactor.InternalChannel.handleIOEvent(InternalChannel.java:50)。org.apache.hc.core5.reactor.AbstractSingleCoreIOReactor.execute(AbstractSingleCoreIOReactor.execute(AbstractSingleCoreIO80))上的org.apache.hc.core5.reactor.SingleCoreIOReactor.doExecute(SingleCoreIOReactor.java:123)上的processEvents(SingleCoreIOReactor.java:173)在org.apache.hc.core5.reactor.IOReactorWorker.run(IOReactorWorker.java:44)在java.lang.Thread.run(Thread.java:748)

如果我打印提供程序和版本,它将打印为 Conscrypt版本1.0JDK 1.8.0_162 ,但仍然无法与http2端点连接

如果我使用带有默认提供程序的jdk9进行连接,则相同的代码块可以完美地工作,在Conscrypt配置中我缺少了什么?

任何帮助表示赞赏

提前致谢


问题答案:

仅用Conscrypt替换默认的JSSE提供程序是不够的。还需要一种TlsStrategy可以利用Conscrypt API 的自定义项。

这适用于Java 1.8和Conscrypt 1.4.1

static class ConscriptClientTlsStrategy implements TlsStrategy {

    private final SSLContext sslContext;

    public ConscriptClientTlsStrategy(final SSLContext sslContext) {
        this.sslContext = Args.notNull(sslContext, "SSL context");
    }

    @Override
    public boolean upgrade(
            final TransportSecurityLayer tlsSession,
            final HttpHost host,
            final SocketAddress localAddress,
            final SocketAddress remoteAddress,
            final Object attachment) {
        final String scheme = host != null ? host.getSchemeName() : null;
        if (URIScheme.HTTPS.same(scheme)) {
            tlsSession.startTls(
                    sslContext,
                    host,
                    SSLBufferMode.STATIC,
                    (endpoint, sslEngine) -> {
                        final SSLParameters sslParameters = sslEngine.getSSLParameters();
                        sslParameters.setProtocols(H2TlsSupport.excludeBlacklistedProtocols(sslParameters.getProtocols()));
                        sslParameters.setCipherSuites(H2TlsSupport.excludeBlacklistedCiphers(sslParameters.getCipherSuites()));
                        H2TlsSupport.setEnableRetransmissions(sslParameters, false);
                        final HttpVersionPolicy versionPolicy = attachment instanceof HttpVersionPolicy ?
                                (HttpVersionPolicy) attachment : HttpVersionPolicy.NEGOTIATE;
                        final String[] appProtocols;
                        switch (versionPolicy) {
                            case FORCE_HTTP_1:
                                appProtocols = new String[] { ApplicationProtocols.HTTP_1_1.id };
                                break;
                            case FORCE_HTTP_2:
                                appProtocols = new String[] { ApplicationProtocols.HTTP_2.id };
                                break;
                            default:
                                appProtocols = new String[] { ApplicationProtocols.HTTP_2.id, ApplicationProtocols.HTTP_1_1.id };
                        }
                        if (Conscrypt.isConscrypt(sslEngine)) {
                            sslEngine.setSSLParameters(sslParameters);
                            Conscrypt.setApplicationProtocols(sslEngine, appProtocols);
                        } else {
                            H2TlsSupport.setApplicationProtocols(sslParameters, appProtocols);
                            sslEngine.setSSLParameters(sslParameters);
                        }
                    },
                    (endpoint, sslEngine) -> {
                        if (Conscrypt.isConscrypt(sslEngine)) {
                            return new TlsDetails(sslEngine.getSession(), Conscrypt.getApplicationProtocol(sslEngine));
                        }
                        return null;
                    });
            return true;
        }
        return false;
    }

}

public static void main(String[] args) throws Exception {
    final SSLContext sslContext = SSLContexts.custom()
            .setProvider(Conscrypt.newProvider())
            .build();
    final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
            .setTlsStrategy(new ConscriptClientTlsStrategy(sslContext))
            .build();
    try (CloseableHttpAsyncClient client = HttpAsyncClients.custom()
            .setVersionPolicy(HttpVersionPolicy.NEGOTIATE)
            .setConnectionManager(cm)
            .build()) {

        client.start();

        final HttpHost target = new HttpHost("nghttp2.org", 443, "https");
        final String requestUri = "/httpbin";
        final HttpClientContext clientContext = HttpClientContext.create();

        final SimpleHttpRequest request = SimpleHttpRequests.GET.create(target, requestUri);
        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(requestUri + "->" + response.getCode() + " " +
                                clientContext.getProtocolVersion());
                        System.out.println(response.getBody());
                        final SSLSession sslSession = clientContext.getSSLSession();
                        if (sslSession != null) {
                            System.out.println("SSL protocol " + sslSession.getProtocol());
                            System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
                        }
                    }

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

                    @Override
                    public void cancelled() {
                        System.out.println(requestUri + " cancelled");
                    }

                });
        future.get();

        System.out.println("Shutting down");
        client.shutdown(CloseMode.GRACEFUL);
    }
}


 类似资料:
  • 问题内容: 我想使用公共密钥加密技术在JavaScript中加密,在PHP中解密。我一直在尝试找到可以完成此任务的库,但是遇到了问题。 我目前正在使用 openpgpjs ,但是我需要所有浏览器的支持,甚至测试页在唯一列为受支持的浏览器(Google Chrome)上都有错误。 关于最终目标的注意事项: TCP连接已受SSL保护。 此保护层的主要目的是防御有意或无意的Web服务器日志记录,崩溃转储

  • 我正在建立一个个人股票平台(不是分布式的)。我想要的一个组件是这个页面上的EPS图: https://eresearch.fidelity.com/eresearch/evaluate/curritials/currence.jhtml?stockspage=currene&symbols=aapl&showpriceline=yes 正如您所看到的,该页面是,所以经过几天的努力,我启用了,现在它

  • 问题内容: 我已经获得了用于加密的Java实现,但是很遗憾,我们是.net商店,并且无法将Java集成到我们的解决方案中。不幸的是,我也不是Java专家,所以我已经为此奋斗了几天,以为我最终会在这里寻求帮助。 我一直在寻找一种与Java加密工作方式相匹配的方法,并且已经找到了在c#中使用RijndaelManaged所需的分辨率。我真的很近。我在c#中返回的字符串与前半部分匹配,但后半部分不同。

  • null 解密(PHP) $IVSIZE=mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256,MCRYPT_MODE_CBC); $iv=mcrypt_create_iv($ivsize,MCRYPT_RAND); mcrypt_decrypt(MCRYPT_RIJNDAEL_256,'test',$encrypt,MCRYPT_MODE_CBC,$iv);

  • 本文介绍如何为 DM 的连接开启加密传输,包括 DM-master,DM-worker,dmctl 组件之间的连接以及 DM 组件与上下游数据库之间的连接。 为 DM-master,DM-worker,dmctl 组件之间的连接开启加密传输 本节介绍如何为 DM-master,DM-worker,dmctl 组件之间的连接开启加密传输。 配置开启加密传输 准备证书。 推荐为 DM-master、D

  • 问题内容: 我正在尝试使用JDK8运行Aspectj- Maven插件。但是它给出了诸如“无法解析类型java.lang.CharSequence的错误。它是从所需的.class文件中间接引用的” 有关如何解决的任何帮助,或者Aspectj-maven-plugin是否支持JDK8。我正在使用AspectJ–Maven插件的1.6版本。 问题答案: 我必须达到相同的目标,而且我疯狂地试图弄清楚这一