Example of Validating a Certification Path using the PKIX algorithm

This is an example of validating a certification path with the PKIX validation algorithm. The example ignores most of the exception handling and assumes that the certification path and public key of the trust anchor have already been created.

First, create the CertPathValidator, as in the following line:

CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

Next create a TrustAnchor object. This object will be used as an anchor for validating the certification path. In this example, the most-trusted CA is specified as a public key and name (name constraints are not applied and are specified as null):

TrustAnchor anchor = new TrustAnchor("O=xyz,C=us", pubkey, null);

Next create a PKIXParameters object. This object will be used to populate the parameters used by the PKIX algorithm. In this example, we pass to the constructor a Set containing a single element - the TrustAnchor that we created in the previous step:

PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));

Next, populate the parameters object with constraints or other parameters used by the validation algorithm. In this example, we enable the explicitPolicyRequired flag and specify a set of initial policy OIDs (the contents of the set are not shown):

// set other PKIX parameters here
params.setExplicitPolicyRequired(true);
params.setInitialPolicies(policyIds);

The final step is to validate the certification path using the input parameter set we have created:

try {
	PKIXCertPathValidatorResult result =
		(PKIXCertPathValidatorResult) cpv.validate(certPath, params);
	PolicyNode policyTree = result.getPolicyTree();
	PublicKey subjectPublicKey = result.getPublicKey();
} catch (CertPathValidatorException cpve) {
	System.out.println("Validation failure, cert["
		+ cpve.getIndex() + "] :" + cpve.getMessage());
}

If the validation algorithm is successful, the policy tree and subject public key resulting from the validation algorithm are obtained using the getPolicyTree and getPublicKey methods of PKIXCertPathValidatorResult.

Otherwise, a CertPathValidatorException is thrown and the caller can catch the exception and print some details about the failure, such as the error message and the index of the certificate that caused the failure.