Example usage for java.security.cert CertificateFactory generateCertPath

List of usage examples for java.security.cert CertificateFactory generateCertPath

Introduction

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

Prototype

public final CertPath generateCertPath(List<? extends Certificate> certificates) throws CertificateException 

Source Link

Document

Generates a CertPath object and initializes it with a List of Certificate s.

Usage

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * PKCS #7 encode a number of certificates.
 *
 * @return The encoding/*from  ww  w  .  j a  va  2  s. c  o m*/
 * @param certs
 *            The certificates
 * @throws CryptoException
 *             If there was a problem encoding the certificates
 */
public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) throws CryptoException {
    try {
        ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>();

        Collections.addAll(encodedCerts, certs);

        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());

        CertPath cp = cf.generateCertPath(encodedCerts);

        return cp.getEncoded(PKCS7_ENCODING);
    } catch (CertificateException e) {
        throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e);
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * PKI Path encode a number of certificates.
 *
 * @return The encoding//  ww w .j a  v  a2 s.c  o m
 * @param certs
 *            The certificates
 * @throws CryptoException
 *             If there was a problem encoding the certificates
 */
public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) throws CryptoException {
    try {
        ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>();

        Collections.addAll(encodedCerts, certs);

        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());

        CertPath cp = cf.generateCertPath(encodedCerts);

        return cp.getEncoded(PKI_PATH_ENCODING);
    } catch (CertificateException e) {
        throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e);
    }
}

From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Create a SignInfo instance with signCertificateChain from samlAuthorityConfig.
 * @param samlAuthorityConfig//from w ww. ja va2  s  . co  m
 * @return created SignInfo.
 */
private static SignInfo getSignInfo(SamlAuthorityConfiguration samlAuthorityConfig) {
    List<Certificate> signingCertificateChain = samlAuthorityConfig.getSigningCertificateChain();

    final CertPath certPath;
    try {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        certPath = certificateFactory.generateCertPath(signingCertificateChain);
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }

    SignInfo signInfo = new SignInfo(samlAuthorityConfig.getAuthorityKey(), certPath, null); // TODO provider

    return signInfo;
}

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  ava  2  s.  c o  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:it.anyplace.sync.core.security.KeystoreHandler.java

public void checkSocketCerificate(SSLSocket socket, String deviceId)
        throws SSLPeerUnverifiedException, CertificateException {
    SSLSession session = socket.getSession();
    List<Certificate> certs = Arrays.asList(session.getPeerCertificates());
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory.generateCertPath(certs);
    Certificate certificate = certPath.getCertificates().get(0);
    checkArgument(certificate instanceof X509Certificate);
    byte[] derData = certificate.getEncoded();
    String deviceIdFromCertificate = derDataToDeviceIdString(derData);
    logger.trace("remote pem certificate =\n{}", derToPem(derData));
    checkArgument(equal(deviceIdFromCertificate, deviceId), "device id mismatch! expected = %s, got = %s",
            deviceId, deviceIdFromCertificate);
    logger.debug("remote ssl certificate match deviceId = {}", deviceId);
}

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//w  w  w . j  a  v a  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:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature/*from w  ww .  j av  a 2 s .  com*/
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:com.vmware.identity.samlservice.impl.CasIdmAccessor.java

@Override
public CertPath getCertificatesForRelyingParty(String relyingParty) {
    logger.debug("getCertificatesForRelyingParty {}", relyingParty);
    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    // only query relying party if it's not null
    // simply return an empty chain for 'null' relying party
    if (relyingParty != null) {
        try {/*from  w  w  w  .  ja  v  a2  s.  co m*/
            // TODO support more than one cert
            RelyingParty rp = client.getRelyingPartyByUrl(tenant, relyingParty);
            Validate.notNull(rp);
            Certificate c = rp.getCertificate();
            Validate.notNull(c);
            certificates.add((X509Certificate) c);
        } catch (Exception e) {
            logger.error("Caught exception ", e);
        }
    }
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        CertPath certPath = certFactory.generateCertPath(certificates);
        return certPath;
    } catch (Exception e) {
        logger.error("Caught exception ", e);
        throw new IllegalStateException(e);
    }
}

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

public OCSPProbe() {
    CertificateFactory certificateFactory = null;

    try {/*from www  .ja  v  a2s .com*/
        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:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*  w w w.  jav  a2s.  co m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.info("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on certificate number "
                + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}