Validating a Certification Path - Java Security

Java examples for Security:Certificate

Description

Validating a Certification Path

import java.io.File;
import java.io.FileInputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertPathValidatorResult;
import java.security.cert.CertificateException;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;

public class Main {
  public static void main(String[] argv) {
    try {
      String filename = System.getProperty("java.home")
          + "/lib/security/cacerts".replace('/', File.separatorChar);
      FileInputStream is = new FileInputStream(filename);
      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      String password = "changeit";
      keystore.load(is, password.toCharArray());

      // Create the parameters for the validator
      PKIXParameters params = new PKIXParameters(keystore);

      // Disable CRL checking since we are not supplying any CRLs
      params.setRevocationEnabled(false);

      CertPathValidator certPathValidator = CertPathValidator
          .getInstance(CertPathValidator.getDefaultType());
      CertPathValidatorResult result = certPathValidator.validate(certPath,
          params);

      PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
      TrustAnchor ta = pkixResult.getTrustAnchor();
      X509Certificate cert = ta.getTrustedCert();
    } catch (Exception e) {
      // Validation failed
    }
  }
}

Related Tutorials