use of java.security.cert.CertPathBuilder in project gitblit by gitblit.
the class X509Utils method verifyChain.
/**
* Verifies a certificate's chain to ensure that it will function properly.
*
* @param testCert
* @param additionalCerts
* @return
*/
public static PKIXCertPathBuilderResult verifyChain(X509Certificate testCert, X509Certificate... additionalCerts) {
try {
// Check for self-signed certificate
if (isSelfSigned(testCert)) {
throw new RuntimeException("The certificate is self-signed. Nothing to verify.");
}
// Prepare a set of all certificates
// chain builder must have all certs, including cert to validate
// http://stackoverflow.com/a/10788392
Set<X509Certificate> certs = new HashSet<X509Certificate>();
certs.add(testCert);
certs.addAll(Arrays.asList(additionalCerts));
// Attempt to build the certification chain and verify it
// Create the selector that specifies the starting certificate
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(testCert);
// Create the trust anchors (set of root CA certificates)
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate cert : additionalCerts) {
if (isSelfSigned(cert)) {
trustAnchors.add(new TrustAnchor(cert, null));
}
}
// Configure the PKIX certificate builder
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
pkixParams.setRevocationEnabled(false);
pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));
// Build and verify the certification chain
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);
// The chain is built and verified
return verifiedCertChain;
} catch (CertPathBuilderException e) {
throw new RuntimeException("Error building certification path: " + testCert.getSubjectX500Principal(), e);
} catch (Exception e) {
throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
}
}
Aggregations