Validating certificate chain in Java from truststore
Asked Answered
T

2

6

I have a certificate chain as der encoded byte[][] array to verify. I also have a truststore file.

After I create X509Certificate[] from that byte array[][] and initializing trustmanager, how will I tell to TrustManager to verify that X509Certificate[]? What is the proper way to do it?

Thanks.

Sample code:

int certVerify(byte certChain[][])
{
   CertificateFactory cf = CertificateFactory.getInstance("X509");
   X509Certificate certx[] = new X509Certificate[10];
   for(int i=0;i<certChain.length;i++)
   {
     certx[i] = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certChain[i]));
   }

   KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load( new FileInputStream("cacerts.jks"),"123456".toCharArray());

   TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   trustManagerFactory.init(keyStore);
}
Tricolor answered 29/4, 2015 at 17:50 Comment(0)
D
10

You'll need to enable OCSP with the necessary system properties, or obtain CRLs for each certificate in the chain, in order to check the revocation status. (Alternatively, you can disable revocation checking, with the attendant risks.)

CertificateFactory cf = CertificateFactory.getInstance("X.509");
List<Certificate> certx = new ArrayList<>(certChain.length);
for (byte[] c : certChain)
  certx.add(cf.generateCertificate(new ByteArrayInputStream(c)));
CertPath path = cf.generateCertPath(certx);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
KeyStore keystore = KeyStore.getInstance("JKS");
try (InputStream is = Files.newInputStream(Paths.get("cacerts.jks"))) {
  keystore.load(is, "changeit".toCharArray());
}
Collection<? extends CRL> crls;
try (InputStream is = Files.newInputStream(Paths.get("crls.p7c"))) {
  crls = cf.generateCRLs(is);
}
PKIXParameters params = new PKIXParameters(keystore);
CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls));
/* If necessary, specify the certificate policy or other requirements 
 * with the appropriate params.setXXX() method. */
params.addCertStore(store);
/* Validate will throw an exception on invalid chains. */
PKIXCertPathValidatorResult r = (PKIXCertPathValidatorResult) validator.validate(path, params);
Diogenes answered 29/4, 2015 at 20:21 Comment(0)
L
1

There is some good information on how to implement one here

Or you could use the BouncyCastle APIs as explained here

Laughingstock answered 29/4, 2015 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.