使用Java编写使用ssl / tls的客户端-服务器应用程序,而又无法使用keytool
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Java编写使用ssl / tls的客户端-服务器应用程序,而又无法使用keytool,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2545字,纯文字阅读大概需要4分钟。
内容图文
![使用Java编写使用ssl / tls的客户端-服务器应用程序,而又无法使用keytool](/upload/InfoBanner/zyjiaocheng/673/136b9352df244199ac40bab7917f0014.jpg)
我打算做的是编写一个使用SSL(TLS)连接来交换数据的客户端服务器应用程序.
由于客户端是可下载的,并且我不能保证可以访问密钥库,因此我正在寻找一种在运行时导入证书的方法.
我需要的:
>一种将服务器的公钥/证书导入客户端应用程序的方法
>一种将服务器的私钥/证书导入服务器应用程序的方法
到目前为止,我发现了什么:
// 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,则必须切换到其他提供商,例如有弹性的城堡支持此.
如果您对密钥库类型没有要求,则可以切换到JKS,它是Java的密钥库,并允许设置受信任的证书(即不属于私钥的一部分).
对于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);
现在,您可以在代码中使用密钥存储,该存储具有服务器的受信任证书而不是私钥.
从代码中的注释中,我注意到您使用OpenSSL创建了PKCS12?
如果您已经拥有p12,则不能为KeyManager使用“ JKS”.
您必须使用PKCS12并将其加载为PKCS12才能在kmf中使用.
因此,您必须在应用中使用2种类型
内容总结
以上是互联网集市为您收集整理的使用Java编写使用ssl / tls的客户端-服务器应用程序,而又无法使用keytool全部内容,希望文章能够帮你解决使用Java编写使用ssl / tls的客户端-服务器应用程序,而又无法使用keytool所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。