5

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

Community
  • 1
  • 1
user1884155
  • 3,616
  • 4
  • 55
  • 108
  • There's a Sun GUI program called `InstallCert` floating around that you should be able to find. I think I posted it either here or in the Oracle Java forums, sorry I can't provide a link at the moment. – user207421 Feb 14 '14 at 23:06

1 Answers1

7

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

nablex
  • 4,635
  • 4
  • 36
  • 51
  • Thanks for pointing me in the right direction! Will keystore.setCertificateEntry add the certificate temporarily (only while this program is running) and locally (only for this application) or will this add the given certificate to my cacerts and thus it will forever be accepted? – user1884155 Feb 14 '14 at 10:56
  • That depends entirely on which keystore you add it to. If you add it to the default cacerts keystore then yes. If you add it to another keystore it will only be active when you use that keystore. – nablex Feb 14 '14 at 12:39
  • If I use KeyStore.getInstance(KeyStore.getDefaultType()), do I get the keystore that links to cacerts, or a completely new empty keystore with no certificates? Or something else? – user1884155 Feb 14 '14 at 15:27
  • 1
    @user1884155, to save a keystore use `KeyStore.store` (as described in the JavaDoc introduction linked from this answer). Getting the default truststore [could be difficult in general](http://stackoverflow.com/a/13660336/372643). – Bruno Feb 14 '14 at 15:46
  • Is it ok to use KeyStore class for a trust store? There is a conceptual difference between a key store and a trust store. – tharinduwijewardane Oct 23 '18 at 11:26