Listing the Most-Trusted Certificate Authorities (CA) in a Key Store - Java Security

Java examples for Security:Certificate

Description

Listing the Most-Trusted Certificate Authorities (CA) in a Key Store

Demo Code

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.Iterator;


public class Main {
  public static void main(String[] args) throws Exception {
    try {//w  ww . j  a  v  a2s.c  om
      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());

      PKIXParameters params = new PKIXParameters(keystore);

      Iterator it = params.getTrustAnchors().iterator();
      for (; it.hasNext();) {
        TrustAnchor ta = (TrustAnchor) it.next();
        // Get certificate
        X509Certificate cert = ta.getTrustedCert();
      }
    } catch (CertificateException e) {
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidAlgorithmParameterException e) {
    } catch (IOException e) {
    }
  }

}

Related Tutorials