Example usage for java.security.cert PKIXParameters PKIXParameters

List of usage examples for java.security.cert PKIXParameters PKIXParameters

Introduction

In this page you can find the example usage for java.security.cert PKIXParameters PKIXParameters.

Prototype

public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException 

Source Link

Document

Creates an instance of PKIXParameters that populates the set of most-trusted CAs from the trusted certificate entries contained in the specified KeyStore .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    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 = "password";
    keystore.load(is, password.toCharArray());

    PKIXParameters params = new PKIXParameters(keystore);

    params.setRevocationEnabled(false);//from   ww w . j  a v a 2s. c o  m

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

    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
    TrustAnchor ta = pkixResult.getTrustAnchor();
    X509Certificate cert = ta.getTrustedCert();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//from  ww w .j a v  a 2 s. com

    CertPath cp = cf.generateCertPath(mylist);

    Certificate trust = cf.generateCertificate(in);
    TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
    params.setRevocationEnabled(false);
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    System.out.println(result);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    List mylist = new ArrayList();

    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//  w  w w.  ja  v a2  s.  c  o  m

    CertPath cp = cf.generateCertPath(mylist);

    FileInputStream kin = new FileInputStream(args[0]);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(kin, args[1].toCharArray());

    PKIXParameters params = new PKIXParameters(ks);
    params.setRevocationEnabled(false);

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

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);

    PublicKey pbk = result.getPublicKey();
    byte[] pkenc = pbk.getEncoded();
    BigInteger pk = new BigInteger(pkenc);
    System.out.println(pk.toString(16));

    TrustAnchor anc = result.getTrustAnchor();
    X509Certificate xc = anc.getTrustedCert();
    System.out.println(xc.getSubjectDN());
    System.out.println(xc.getIssuerDN());

}

From source file:CAList.java

/**
 * <p><!-- Method description --></p>
 *
 *
 * @param args//from w  w w  .j  av a  2  s.  com
 */
public static void main(String[] args) {
    try {
        // Load the JDK's cacerts keystore file
        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());

        // This class retrieves the most-trusted CAs from the keystore
        PKIXParameters params = new PKIXParameters(keystore);

        // Get the set of trust anchors, which contain the most-trusted CA certificates
        Iterator it = params.getTrustAnchors().iterator();
        for (; it.hasNext();) {
            TrustAnchor ta = (TrustAnchor) it.next();

            // Get certificate
            X509Certificate cert = ta.getTrustedCert();
            System.out.println("<issuer>" + cert.getIssuerDN() + "</issuer>\n");
        }
    } catch (CertificateException e) {
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidAlgorithmParameterException e) {
    } catch (IOException e) {
    }
}

From source file:Main.java

public static PKIXCertPathValidatorResult validateCertificate(X509Certificate entity,
        X509Certificate intermediate, X509Certificate CA) throws Exception {
    /*  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
      ks.load(null, null);/*from  www  .  j  a v a 2 s .  c  o  m*/
      String alias = "validationCA";
      ks.setCertificateEntry(alias, CA);
            
     */
    /*  KeyStore intermediatesStore = KeyStore.getInstance(KeyStore.getDefaultType());
    intermediatesStore.load(null, null);
    String alias_intermediate = "validationIntermediate";
    intermediatesStore.setCertificateEntry(alias_intermediate, intermediate);*//*
                                                                                        
                                                                                        
                                                                                X509CertSelector target = new X509CertSelector();
                                                                                target.setCertificate(entity);
                                                                                PKIXBuilderParameters params = new PKIXBuilderParameters(ks, target);
                                                                                ArrayList<X509Certificate> chain = new ArrayList<>();
                                                                                chain.add(intermediate);
                                                                                chain.add(intermediate);
                                                                                CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
                                                                                params.addCertStore(CertStore.getInstance("Collection", intermediates));
                                                                                CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
                                                                                 *//*
                                                                                    * If build() returns successfully, the certificate is valid. More details
                                                                                    * about the valid path can be obtained through the PKIXBuilderResult.
                                                                                    * If no valid path can be found, a CertPathBuilderException is thrown.
                                                                                    *//*
                                                                                          PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params);
                                                                                          return result;*/

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory
            .generateCertPath(Arrays.asList(new X509Certificate[] { entity, intermediate }));

    TrustAnchor trustAnchor = new TrustAnchor(CA, null);

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

    PKIXParameters pkixParams = new PKIXParameters(Collections.singleton(trustAnchor));
    pkixParams.setRevocationEnabled(true);

    return (PKIXCertPathValidatorResult) cpv.validate(certPath, pkixParams);
}

From source file:be.apsu.extremon.probes.ocsp.OCSPProbe.java

public OCSPProbe() {
    CertificateFactory certificateFactory = null;

    try {/*from w  w  w.  j a va  2 s.  co m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException cex) {
        log("Don't Have Crypto Libs:" + cex.getMessage());
        System.exit(1);
    }

    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("certificate"))));
        trustAnchorCert = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("trustanchor"))));
    } catch (CertificateException cex) {
        log("certificate and trustanchor required in config:" + cex.getMessage());
        System.exit(2);
    }

    this.delay = confInt("delay", DEFAULT_DELAY);

    try {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(this.certificate);
        this.certificatePath = (CertPath) certificateFactory.generateCertPath(certs);

        TrustAnchor trustAnchor = new TrustAnchor(this.trustAnchorCert, null);
        Set<TrustAnchor> trustedCertsSet = new HashSet<TrustAnchor>();
        trustedCertsSet.add(trustAnchor);

        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        certSet.add(this.trustAnchorCert);
        CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
        CertStore store = CertStore.getInstance("Collection", storeParams);

        pkixParams = new PKIXParameters(trustedCertsSet);
        pkixParams.addCertStore(store);

        Security.setProperty("ocsp.enable", "true");
        Security.setProperty("ocsp.responderURL", confStr("url"));
        Security.setProperty("ocsp.responderCertSubjectName",
                this.trustAnchorCert.getSubjectX500Principal().getName());

        this.certificatePathValidator = CertPathValidator.getInstance("PKIX");
    } catch (InvalidAlgorithmParameterException iaex) {
        log("Invalid Algorithm Parameter:" + iaex.getMessage());
        System.exit(3);
    } catch (CertificateException cex) {
        log("Certificate Exception:" + cex.getMessage());
        System.exit(4);
    } catch (NoSuchAlgorithmException nsaex) {
        log("No Such Algorithm:" + nsaex.getMessage());
        System.exit(5);
    } catch (Exception ex) {
        log(ex.getMessage());
        System.exit(6);
    }

    start();
    log("Initialized");
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida si el certificado es apocrifo, no valido ante el SAT
 *
 * @param cert Certificado a validar/*from  ww w  .  j a  va  2s. com*/
 * @return true si el certificado es apocrifo, en otro caso false
 */
public boolean validateCertificate() {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List mylist = new ArrayList();
        TrustAnchor anchor = new TrustAnchor(
                (java.security.cert.X509Certificate) importCertificate(cerInputStream), null);
        mylist.add(certificado);
        CertPath cp = cf.generateCertPath(mylist);
        PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
        params.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        return true;
    } catch (Exception ex) {
        System.out.println("Expecion causada a proposito :P");
    }
    return false;
}

From source file:com.vangent.hieos.services.sts.util.STSUtil.java

/**
 *
 * @param cert//from  w ww .j a va  2 s . c  om
 * @param trustStore
 * @throws STSException
 */
public static void validateCertificate(X509Certificate cert, KeyStore trustStore) throws STSException {
    try {
        // To check the validity of the dates
        cert.checkValidity();
    } catch (CertificateExpiredException ex) {
        throw new STSException("Certificate expired: " + ex.getMessage());
    } catch (CertificateNotYetValidException ex) {
        throw new STSException("Certificate not yet valid: " + ex.getMessage());
    }

    // Check the chain.
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List<X509Certificate> mylist = new ArrayList<X509Certificate>();
        mylist.add(cert);
        CertPath cp = cf.generateCertPath(mylist);
        PKIXParameters params = new PKIXParameters(trustStore);
        // FIXME: Add revocation checking.
        params.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
        PKIXCertPathValidatorResult pkixCertPathValidatorResult = (PKIXCertPathValidatorResult) cpv.validate(cp,
                params);
        if (logger.isDebugEnabled()) {
            logger.debug(pkixCertPathValidatorResult);
        }
    } catch (Exception ex) {
        throw new STSException("Exception while validating Certificate: " + ex.getMessage());
    }
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

/**
 * Validates the specified certificate path incl. OCSP revocation check
 * //  w  w  w  .ja v  a2s.  c om
 * @param truststore
 * @return true if all certificate is valid
 * @throws Exception 
 */
private boolean isCertValid(KeyStore truststore) throws Exception {
    List<X509Certificate> certlist = new ArrayList<X509Certificate>();
    certlist.add(signerCert);

    PKIXParameters params = new PKIXParameters(truststore);

    // Activate certificate revocation checking
    params.setRevocationEnabled(true);

    // Activate OCSP
    Security.setProperty("ocsp.enable", "true");

    // Activate CRLDP
    System.setProperty("com.sun.security.enableCRLDP", "true");

    // Ensure that the ocsp.responderURL property is not set.
    if (Security.getProperty("ocsp.responderURL") != null) {
        throw new Exception("The ocsp.responderURL property must not be set");
    }

    CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());

    cpv.validate(CertificateFactory.getInstance("X.509").generateCertPath(certlist), params);

    return true; // No Exception, all fine..
}

From source file:net.sf.dsig.verify.XmldsigVerifier.java

public boolean isCertificatePathValid() throws VerificationException {
    if (trustAnchors == null) {
        throw new ConfigurationException("TrustAnchors must be set");
    }// ww  w.  j a  v a  2s.c om

    try {
        PKIXParameters parameters = new PKIXParameters(trustAnchors);
        parameters.setRevocationEnabled(false);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        CertPath certPath = cf.generateCertPath(Arrays.asList(getCertificateChain()));

        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult res = (PKIXCertPathValidatorResult) cpv.validate(certPath, parameters);

        logger.debug("Certificate path validation succeeded; result=" + res.toString());

        return true;
    } catch (CertPathValidatorException e) {
        logger.info("Certificate path validation failed", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        throw new ConfigurationException("PKIX algorithm not found; should not happen");
    } catch (CertificateException e) {
        throw new ConfigurationException("X.509 certificate factory not found; should not happen");
    } catch (NoSuchAlgorithmException e) {
        throw new ConfigurationException("PKIX algorithm not found; should not happen");
    }
}