Programmatically add a self-signed certificate to your keystore/truststore

耗尽温柔 提交于 2019-12-21 05:43:17

问题


I saw this question (and others) where it is explained how to add a (self-signed) certificate to your keystore/cacerts manually by using the commandline. When doing this, you can set up a secured connection with a server without a signed certificate, if you were given the certificate (.cert file). This is can be useful for testing purposes.

I would like to program this, so users don't need to do this manually. The basic concept would be the following: The user has a local copy of the .cert file, and gives my program the path to where that file resides in his file system. My program fetches the file and adds it to the keystore.

My question is: how to add this certificate to the keystore within my program, so that the turstmanager will accept it as a trustworthy/signed certificate, given the (path) to the .cert file? Are there any tutorials or code snippets regarding to this problem?

PS: I do NOT need the "accept all certificates" trustmanager trick as described here


回答1:


Rather simple:

InputStream input = ...;
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(input);
KeyStore keystore = ...;
keystore.setCertificateEntry(alias, cert);

Loading and storing the keystore is evident from the javadoc: http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html



来源:https://stackoverflow.com/questions/21775408/programmatically-add-a-self-signed-certificate-to-your-keystore-truststore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!