Validating certificate chain in Java from truststore
14,562
Solution 1
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);
Solution 2
There is some good information on how to implement one here
Or you could use the BouncyCastle APIs as explained here
Author by
vkx
Updated on June 04, 2022Comments
-
vkx almost 2 years
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); }