我打算做的是编写一个使用 SSL (TLS) 连接交换数据的客户端-服务器应用程序。
由于客户端是可下载的,而且我不能保证可以访问 keystore ,所以我正在寻找一种在运行时导入证书的方法。
我需要什么:
- 将服务器的公共(public) key /证书导入客户端应用程序的方法
- 一种将服务器的私钥/证书导入服务器应用程序的方法
到目前为止我发现了什么:
// load the server's public crt (pem), exported from a https website
CertificateFactory cf = CertificateFactory.getInstance("X509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(new
FileInputStream("C:\\certificate.crt"));
// load the pkcs12 key generated with openssl out of the server.crt and server.key (private) (if the private key is stored in the pkcs file, this is not a solution as I need to ship it with my application)
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream("C:\\certificate.pkcs"), "password".toCharArray());
ks.setCertificateEntry("Alias", cert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "password".toCharArray());
// create SSLContext to establish the secure connection
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
这对我不起作用,因为我收到一个错误:
java.security.KeyStoreException: TrustedCertEntry not supported at ks.setCertificateEntry("Alias", cert);
此外,我认为 pkcs12 用于存储私钥,这不是我想要的。
我是 java 的新手,现在我真的被那个问题困住了。
提前致谢
和夫
最佳答案
Sun 的#PKCS12
实现不允许存储不属于私钥链的可信证书。
如果您需要使用#PKCS12
,您必须切换到不同的提供商,例如Bouncy CaSTLe 支持这一点。
如果您对 keystore 类型没有要求,您可以切换到 JKS
,它是 java 的 keystore 并允许设置受信任的证书(即不是私钥的一部分)。
对于 JKS
,您可以使用默认提供程序,即 SUN。
更新:
因此,您的代码必须更改如下:
//Create a temp keystore with the server certificate
KeyStore ksTemp = KeyStore.getInstance("JKS");
ksTemp.load(null, null);//Initialize it
ksTemp.setCertificateEntry("Alias", cert);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
// save the temp keystore
ks.store(bOut, password);
//Now create the keystore to be used by jsse
Keystore store = KeyStore.getInstance("JKS");
store.load(new ByteArrayInputStream(bOut.toByteArray()), password);
现在您在代码中使用 keystore store
,它具有服务器的可信证书而不是私钥。
从代码中的注释中,我注意到您有一个使用 OpenSSL 创建的 PKCS12?
如果您已经有 p12,那么您不能将“JKS”用于 KeyManager。
您必须使用 PKCS12
并将其加载为 PKCS12
才能在 kmf
中使用它。
所以你必须在你的应用中使用两种类型
关于java - 使用 java 编写使用 ssl/tls 的客户端-服务器应用程序,但不能使用 keytool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556377/