Example of Building a Certification Path using the PKIX algorithm
This example shows how to build a certification path validated
against the PKIX algorithm. Some details have been omitted, such as
exception handling, and the creation of the trust anchors and certificates
for populating the CertStore.
First, create the CertPathBuilder, as in the following example:
CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");
This call creates a CertPathBuilder object that
returns paths validated against the PKIX algorithm.
The next step is to create a PKIXBuilderParameters object. This object is used to populate
the PKIX parameters used by the CertPathBuilder:
// Create parameters object, passing it a Set of
// trust anchors for anchoring the path
// and a target subject DN.
X509CertSelector targetConstraints = new X509CertSelector();
targetConstraints.setSubject("CN=alice,O=xyz,C=us");
PKIXBuilderParameters params =
new PKIXBuilderParameters(trustAnchors, targetConstraints);
The next step is to specify the CertStore that
the CertPathBuilder uses to look for certificates
and CRLs. For this example, we will populate a Collection CertStore with the certificates and CRLs:
CollectionCertStoreParameters ccsp =
new CollectionCertStoreParameters(certsAndCrls);
CertStore store = CertStore.getInstance("Collection", ccsp);
params.addCertStore(store);
The next step is to build the certification path using the input parameter set we have created:
try {
PKIXCertPathBuilderResult result =
(PKIXCertPathBuilderResult) cpb.build(params);
CertPath cp = result.getCertPath();
} catch (CertPathBuilderException cpbe) {
System.out.println("build failed: " + cpbe.getMessage());
}
If the CertPathBuilder cannot build a path that
meets the supplied parameters it will throw a CertPathBuilderException. Otherwise, the validated certification path can be obtained from
the PKIXCertPathBuilderResult using the getCertPath method.