Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trust a certificate authority in Java?

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.

like image 225
Dan Avatar asked Oct 19 '22 23:10

Dan


1 Answers

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.

like image 137
poida Avatar answered Oct 22 '22 13:10

poida