6

I am working with X509 certificates in Java. Given a certificate is it possible to find all other certificates in the signing hierarchy until you reach the root certificate?

I have a certificate file (with a .cer extension) and I want to extract the parent signing certificate. I want to keep finding the parent of that certificate untill I get the final root certificate, which is self signed.

I have checked the X509Certificate certificate APIs and relevant APIs in java.security.cert but could not find anything useful.

culix
  • 10,188
  • 6
  • 36
  • 52
user496934
  • 3,822
  • 10
  • 45
  • 64
  • 1
    possible duplicate of [How to generate intermediate and root cert from an existing leaf certificate?](http://stackoverflow.com/questions/11076491/how-to-generate-intermediate-and-root-cert-from-an-existing-leaf-certificate) – Eugene Mayevski 'Callback Jun 19 '12 at 09:14
  • 1
    There's no reliable way to do this. See my answer on http://stackoverflow.com/a/11076955/47961 – Eugene Mayevski 'Callback Jun 19 '12 at 09:15
  • 1
    Did you try [java.security.KeyStore#getCertificateChain()](http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html#getCertificateChain(java.lang.String)) ? – Zaki Jun 19 '12 at 11:36

1 Answers1

2

That is not hard - assuming you've somehow/out of band got all the intermediate certificates and the root cert in one or more keychains.

Have a look at

http://codeautomate.org/blog/2012/02/certificate-validation-using-java/

for a code snipped which does just that. The key bit is in validateKeyChain() and basically consists of

   cert = cert-to-validate
   while(not self signed) {
       extract issuer from cert
       scan keychain(s) to find cert with a subject equal to the issuer
       if none found - error
       check if the signature is correct.
       cert = issuers_cert
   }
   if not at the top/root - error

As to how you get the intermediate/root certificates - that is a different issue. Note that this code is a little bit naive - and does not quite understand cross-signing. The java pkix calls though though - BouncyCastle has an example.

You can generally build the root certs into a key chain; but the intermediate certificates often need to be 'gathered' or discovered more dynamically. This generally requires querying the SSL stack during TLS or similar.

Dirk-Willem van Gulik
  • 7,566
  • 2
  • 35
  • 40