仅使用 CA 证书且无密钥库使用 SSLContext [英] Using SSLContext with just a CA certificate and no keystore

查看:34
本文介绍了仅使用 CA 证书且无密钥库使用 SSLContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置一个 javax.net.ssl.SSLContext 以在 Jersey 客户端应用程序中使用.我想要做的就是接受自定义根 ca 证书的上下文.真的没有办法生成keystore文件并导入CA证书吗?

I need to setup a javax.net.ssl.SSLContext for use in a Jersey-Client application. All I want to do is the context to accept a custom root ca certificate. Is is really true that there is no way around of generating a keystore file and importing the CA certificate?

推荐答案

确实没有办法生成密钥库文件并导入 CA 证书?

Is is really true that there is no way around of generating a keystore file and importing the CA certificate?

有一些方法可以在没有密钥库文件的情况下执行此操作,但是由于您必须以一种或另一种方式加载您想要信任的 CA 证书,因此您必须以某种方式加载文件或资源.

There are way to do it without a keystore file, but since you would have to load the CA certificate you want to trust one way or another, you'll have to load a file or resource somehow.

(您当然也可以实现自己的 TrustManager,它使所有调用都使用认证路径 API,而根本不使用 KeyStore API,但这只会增加代码的复杂性,而不是减少它.您还需要了解 Java PKI 程序员指南以正确执行此操作.)

(You could also certainly implement your own TrustManager that makes all the calls to use the Certification Path API, without using the KeyStore API at all, but that would only increase the complexity of your code, not reduce it. You would also need to understand the Java PKI Programmer's Guide to do this correctly.)

如果你真的不想要一个keystore文件,你可以在内存中使用KeyStore API并直接加载证书.

If you really don't want a keystore file, you could use the KeyStore API in memory and load the certificate directly.

这些方面的东西应该可以工作(未测试):

Something along these lines should work (not tested):

InputStream is = new FileInputStream("cacert.crt");
// You could get a resource as a stream instead.

CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate caCert = (X509Certificate)cf.generateCertificate(is);

TrustManagerFactory tmf = TrustManagerFactory
    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null); // You don't need the KeyStore instance to come from a file.
ks.setCertificateEntry("caCert", caCert);

tmf.init(ks);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);

(记得关闭一切并处理异常.)

(Remember to close everything and handle the exceptions.)

以这种方式加载证书还是将证书从密钥库文件加载到类似的KeyStore 实例中更方便,由您决定.

Whether loading the certificate this way or loading the certificate into a similar KeyStore instance from a keystore file is more convenient is up to you to decide.

这篇关于仅使用 CA 证书且无密钥库使用 SSLContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆