How to trust a certificate authority in Java?
Asked Answered
S

1

6

My application connects to an SSL web service which uses a certificate to verify its identity. Recently, this certificate changed and since it is not signed by a trusted authority, part of my application failed. The service's advice to protect against this situation in the future is that I should start trusting the existing certificate's signing authority, instead of the individual certificates.

How may this be achieved in Java?

Currently I'm adding the certificate they provide into a keystore using keytool and composing it into a TrustManagerFactory something like:

public static TrustManager[] getTrustManagers() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
    tks.load(StarTrustManagerFactory.class.getResourceAsStream("webservice.ks"), "password".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);
    return tmf.getTrustManagers();
}; 

Is there a way of adapting this approach to return a TrustManager which trusts the signing authority of the certificates I have? Additionally, how can I extract the information regarding the signer of the certificate from the certificate I have?

Thanks, Dan.

Simplehearted answered 29/10, 2014 at 11:30 Comment(1)
See javarevisited.blogspot.de/2012/09/… - you trust any certificate included in your truststore.Jacktar
M
3

Assuming that code posted worked before the certificate changed, leave it as is. Instead modify the webservice.ks keystore and import the intermediate and root ca certificates of the site you are connecting to.

You can get these certificates by visiting the address in a web browser and saving them to disk. For how you'd do this in firefox, see https://superuser.com/a/97203/172370. However at step 4 in the linked instructions, select the root/intermediate ca certs to export (click in the certificate hierarchy box on the desired one).

Then assuming the .ks file is a jks keystore, use keytool to import the certificates into the keystore.

Update: ignore what I said about the intermediate certificate, you shouldn't need it (see Does a truststore need the sub-ca certificate?). Just import the root ca certificate.

Mayor answered 29/10, 2014 at 11:39 Comment(2)
Thanks. I see now how it should work. Unfortunately, with the certificate I get from accessing the web service with a browser, it is alone in its certificate hierarchy. So I should go back to them and ask them for the CA's certificate or the root/intermediary? Just clarifying the terminology I should use. Thanks!Simplehearted
Sounds like either the certificate wasn't generated by a CA or their web server isn't configured correctly. You may need to raise this with the web service admins.Mayor

© 2022 - 2024 — McMap. All rights reserved.