Example usage for java.security.cert CertPathValidator getInstance

List of usage examples for java.security.cert CertPathValidator getInstance

Introduction

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

Prototype

public static CertPathValidator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a CertPathValidator object that implements the specified algorithm.

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  www  .  j  av  a 2  s  .  co 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);//  w ww. j a  v  a2  s.  co m

    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);/*from  w  w w.ja  v a  2s . c om*/

    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: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   w  ww. j a  va2 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 {//  w w  w.  j  a  v a  2s.  c o 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 w  w  w. j  a va  2s . c om
 * @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 v  a 2s.c  o  m*/
 * @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:net.sf.dsig.verify.XmldsigVerifier.java

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

    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");
    }
}

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

/**
 * Validates the specified certificate path incl. OCSP revocation check
 * /*from   w w  w.  j  a v a2s .c o  m*/
 * @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:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java

/**
 * Validate a given certificate chain./*  www  . j  ava  2s  .  c om*/
 * @see Crypto#validateCertPath(java.security.cert.X509Certificate[])
 */
public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
    boolean ok = false;
    try {
        // Generate cert path
        List<X509Certificate> certList = Arrays.asList(certs);
        CertPath path = this.getCertificateFactory().generateCertPath(certList);

        HashSet<TrustAnchor> set = new HashSet<TrustAnchor>();

        if (certs.length == 1) // Use factory certs
        {
            String alias = _factory.getAliasForX509Cert(certs[0].getIssuerDN().getName(),
                    certs[0].getSerialNumber());
            if (alias == null) {
                _logger.debug("Certificate not trusted");
                return false;
            }

            X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
            TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
            set.add(anchor);
        } else {
            // Add certificates from the keystore
            Enumeration aliases = _factory.getAliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
                TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
                set.add(anchor);
            }
        }

        PKIXParameters param = new PKIXParameters(set);
        param.setRevocationEnabled(false);
        Provider provider = _factory.getKeyStore().getProvider();
        String sProvider = null;
        CertPathValidator certPathValidator = null;
        if (provider != null) {
            sProvider = provider.getName();
        }
        if (sProvider == null || sProvider.length() == 0) {
            certPathValidator = CertPathValidator.getInstance("PKIX");
        } else {
            certPathValidator = CertPathValidator.getInstance("PKIX", sProvider);
        }
        certPathValidator.validate(path, param);
        ok = true;
    } catch (NoSuchProviderException e) {
        _logger.warn("No such provider", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (NoSuchAlgorithmException e) {
        _logger.warn("No such algorithm", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (InvalidAlgorithmParameterException e) {
        _logger.warn("Invalid algorithm param", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertificateException e) {
        _logger.warn("Invalid certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (ClassCastException e) {
        _logger.warn("Certificate is not an X509Certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertPathValidatorException e) {
        _logger.warn("Could not validate Cert Path", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CryptoException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    }
    return ok;
}