Programmatically add a self-signed certificate to a keystore / trust store

I saw this question (and others) explaining how to add a (self-signed) certificate to your / cacerts keystore manually using the command line. At the same time, you can configure a secure connection to the server without a signed certificate if you were provided with a certificate (.cert file). This may be useful for testing purposes.

I would like to program this, so users do not need to do this manually. The basic concept will be this: the user has a local copy of the .cert file and provides my program with a path to where this file is located in its file system. My program extracts the file and adds it to the keystore.

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

PS: I don’t need the trust manager’s “accept all certificates” trick as described here

+4
source share
1 answer

Rather simple:

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

Downloading and saving the keystore is obvious from javadoc: http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html

+6
source

Source: https://habr.com/ru/post/1526904/


All Articles