当您不需要提供证书时,为SSL连接配置TcpNetClientConnectionFactory的正确方法是什么?

时间:2017-10-23 18:46:06

标签: java spring ssl spring-integration

在使用SSL配置TCP连接时,基于spring文档,我们使用自己的TcpSSLContextSupport实例,因为DefaultTcpSSLContextSupport需要初始化客户端证书。这是我们的bean配置:

private static final int SERIALIZER_HEADER_SIZE = 2;

@Bean
public ByteArrayLengthHeaderSerializer byteArrayLengthHeaderSerializer() {
    return new ByteArrayLengthHeaderSerializer(SERIALIZER_HEADER_SIZE);
}

@Bean
public AbstractClientConnectionFactory tcpClientConnectionFactory() {
    TcpNetClientConnectionFactory connFactory =
        new TcpNetClientConnectionFactory(props.getUrl(), props.getPort());
    connFactory.setSerializer(byteArrayLengthHeaderSerializer());
    connFactory.setDeserializer(byteArrayLengthHeaderSerializer());
    connFactory.setSoTimeout(props.getSoTimeout());

    if (props.isUseSSL()) {
        connFactory.setTcpSocketFactorySupport(new DefaultTcpNetSSLSocketFactorySupport(() -> {
            return SSLContext.getDefault();
        }));
    }

    return connFactory;
}

由于客户端证书是已知证书,我们不需要提供自己的密钥库和信任库,这是在创建TCP连接时正确配置SSL的正确方法吗?

1 个答案:

答案 0 :(得分:1)

是的,这正是将自定义SSLContext注入ConnectionFactory的方式。

你也可以考虑"信任所有"在你的背景下:

    TrustManager[] trustAllCerts = new TrustManager[] { 
        new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] myTrustedAnchors = new X509Certificate[0];  
                return myTrustedAnchors;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {}

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    return sc;