Example usage for javax.xml.crypto.dsig.dom DOMValidateContext DOMValidateContext

List of usage examples for javax.xml.crypto.dsig.dom DOMValidateContext DOMValidateContext

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig.dom DOMValidateContext DOMValidateContext.

Prototype

public DOMValidateContext(Key validatingKey, Node node) 

Source Link

Document

Creates a DOMValidateContext containing the specified key and node.

Usage

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException,
        TransformerException, MarshalException, XMLSignatureException, JAXBException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    List<String> signatureResourceNames = getSignatureResourceNames(url);
    if (signatureResourceNames.isEmpty()) {
        LOG.debug("no signature resources");
    }/*  w ww  . j  a va2s . c  o m*/
    for (String signatureResourceName : signatureResourceNames) {
        Document signatureDocument = getSignatureDocument(url, signatureResourceName);
        if (null == signatureDocument) {
            continue;
        }

        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (0 == signatureNodeList.getLength()) {
            return null;
        }
        Node signatureNode = signatureNodeList.item(0);

        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);
        domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
        OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);

        if (!valid) {
            LOG.debug("not a valid signature");
            continue;
        }

        /*
         * Check the content of idPackageObject.
         */
        List<XMLObject> objects = xmlSignature.getObjects();
        XMLObject idPackageObject = null;
        for (XMLObject object : objects) {
            if ("idPackageObject".equals(object.getId())) {
                idPackageObject = object;
                break;
            }
        }
        if (null == idPackageObject) {
            LOG.debug("idPackageObject ds:Object not present");
            continue;
        }
        List<XMLStructure> idPackageObjectContent = idPackageObject.getContent();
        Manifest idPackageObjectManifest = null;
        for (XMLStructure content : idPackageObjectContent) {
            if (content instanceof Manifest) {
                idPackageObjectManifest = (Manifest) content;
                break;
            }
        }
        if (null == idPackageObjectManifest) {
            LOG.debug("no ds:Manifest present within idPackageObject ds:Object");
            continue;
        }
        LOG.debug("ds:Manifest present within idPackageObject ds:Object");
        List<Reference> idPackageObjectReferences = idPackageObjectManifest.getReferences();
        Set<String> idPackageObjectReferenceUris = new HashSet<String>();
        Set<String> remainingIdPackageObjectReferenceUris = new HashSet<String>();
        for (Reference idPackageObjectReference : idPackageObjectReferences) {
            idPackageObjectReferenceUris.add(idPackageObjectReference.getURI());
            remainingIdPackageObjectReferenceUris.add(idPackageObjectReference.getURI());
        }
        LOG.debug("idPackageObject ds:Reference URIs: " + idPackageObjectReferenceUris);
        CTTypes contentTypes = getContentTypes(url);
        List<String> relsEntryNames = getRelsEntryNames(url);
        for (String relsEntryName : relsEntryNames) {
            LOG.debug("---- relationship entry name: " + relsEntryName);
            CTRelationships relationships = getRelationships(url, relsEntryName);
            List<CTRelationship> relationshipList = relationships.getRelationship();
            boolean includeRelationshipInSignature = false;
            for (CTRelationship relationship : relationshipList) {
                String relationshipType = relationship.getType();
                STTargetMode targetMode = relationship.getTargetMode();
                if (null != targetMode) {
                    LOG.debug("TargetMode: " + targetMode.name());
                    if (targetMode == STTargetMode.EXTERNAL) {
                        /*
                         * ECMA-376 Part 2 - 3rd edition
                         * 
                         * 13.2.4.16 Manifest Element
                         * 
                         * "The producer shall not create a Manifest element that references any data outside of the package."
                         */
                        continue;
                    }
                }
                if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) {
                    continue;
                }
                String relationshipTarget = relationship.getTarget();
                String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/"));
                String streamEntry = baseUri + relationshipTarget;
                LOG.debug("stream entry: " + streamEntry);
                streamEntry = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(streamEntry));
                LOG.debug("normalized stream entry: " + streamEntry);
                String contentType = getContentType(contentTypes, streamEntry);
                if (relationshipType.endsWith("customXml")) {
                    if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) {
                        LOG.debug("skipping customXml with content type: " + contentType);
                        continue;
                    }
                }
                includeRelationshipInSignature = true;
                LOG.debug("content type: " + contentType);
                String referenceUri = streamEntry + "?ContentType=" + contentType;
                LOG.debug("reference URI: " + referenceUri);
                if (false == idPackageObjectReferenceUris.contains(referenceUri)) {
                    throw new RuntimeException(
                            "no reference in idPackageObject ds:Object for relationship target: "
                                    + streamEntry);
                }
                remainingIdPackageObjectReferenceUris.remove(referenceUri);
            }
            String relsReferenceUri = "/" + relsEntryName
                    + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
            if (includeRelationshipInSignature
                    && false == idPackageObjectReferenceUris.contains(relsReferenceUri)) {
                LOG.debug("missing ds:Reference for: " + relsEntryName);
                throw new RuntimeException("missing ds:Reference for: " + relsEntryName);
            }
            remainingIdPackageObjectReferenceUris.remove(relsReferenceUri);
        }
        if (false == remainingIdPackageObjectReferenceUris.isEmpty()) {
            LOG.debug("remaining idPackageObject reference URIs" + idPackageObjectReferenceUris);
            throw new RuntimeException("idPackageObject manifest contains unknown ds:References: "
                    + remainingIdPackageObjectReferenceUris);
        }

        X509Certificate signer = keySelector.getCertificate();
        signers.add(signer);
    }
    return signers;
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;/*  www .j av a 2 s .  com*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            break;
        }
    }
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    if (null == zipEntry) {
        return signatureInfos;
    }
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
    NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
        Element signatureElement = (Element) signatureNodeList.item(idx);
        xadesValidation.prepareDocument(signatureElement);

        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        ZIPURIDereferencer dereferencer = new ZIPURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);
        if (!valid) {
            continue;
        }

        // check whether all files have been signed properly
        SignedInfo signedInfo = xmlSignature.getSignedInfo();
        @SuppressWarnings("unchecked")
        List<Reference> references = signedInfo.getReferences();
        Set<String> referenceUris = new HashSet<String>();
        for (Reference reference : references) {
            String referenceUri = reference.getURI();
            referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8"));
        }
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (ODFUtil.isSignatureFile(zipEntry)) {
                continue;
            }
            if (!referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ZIP entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

        if (null != originalDocument) {
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    /*
                       * We skip XAdES and eID identity ds:Reference.
                       */
                    continue;
                }
                String digestAlgo = reference.getDigestMethod().getAlgorithm();
                LOG.debug("ds:Reference digest algo: " + digestAlgo);
                String referenceUri = reference.getURI();
                LOG.debug("ds:Reference URI: " + referenceUri);
                byte[] digestValue = reference.getDigestValue();

                org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature(
                        documentSignaturesDocument, "",
                        org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
                        Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);
                xmldsig.addDocument(referenceUri, null, digestAlgo);
                ResourceResolverSpi zipResourceResolver = new ZIPResourceResolver(originalDocument);
                xmldsig.addResourceResolver(zipResourceResolver);
                org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo();
                org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0);
                apacheReference.generateDigestValue();
                byte[] originalDigestValue = apacheReference.getDigestValue();
                if (!Arrays.equals(originalDigestValue, digestValue)) {
                    throw new RuntimeException("not original document");
                }
            }
            /*
             * So we already checked whether no files were changed, and that
             * no files were added compared to the original document. Still
             * have to check whether no files were removed.
             */
            ZipInputStream originalZipInputStream = new ZipInputStream(
                    new ByteArrayInputStream(originalDocument));
            ZipEntry originalZipEntry;
            Set<String> referencedEntryNames = new HashSet<String>();
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    continue;
                }
                referencedEntryNames.add(reference.getURI());
            }
            while (null != (originalZipEntry = originalZipInputStream.getNextEntry())) {
                if (ODFUtil.isSignatureFile(originalZipEntry)) {
                    continue;
                }
                if (!referencedEntryNames.contains(originalZipEntry.getName())) {
                    LOG.warn("missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                    throw new RuntimeException(
                            "missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                }
            }
        }

        X509Certificate signer = keySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature,
                signatureElement, signer);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java

private static boolean _checkSignature(@Nonnull @WillClose final InputStream aEntityInputStream)
        throws Exception {
    try {/*from w  ww.j av a2  s .c om*/
        // Get response from servlet
        final Document aDocument = DOMReader.readXMLDOM(aEntityInputStream);

        // We make sure that the XML is a Signed. If not, we don't have to check
        // any certificates.

        // Find Signature element.
        final NodeList aNodeList = aDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (aNodeList == null || aNodeList.getLength() == 0)
            throw new IllegalArgumentException("Element <Signature> not found in SMP XML response");

        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        final X509KeySelector aKeySelector = new X509KeySelector();
        final DOMValidateContext aValidateContext = new DOMValidateContext(aKeySelector, aNodeList.item(0));
        final XMLSignatureFactory aSignatureFactory = XMLSignatureFactory.getInstance("DOM");

        // Unmarshal the XMLSignature.
        final XMLSignature aSignature = aSignatureFactory.unmarshalXMLSignature(aValidateContext);

        // Validate the XMLSignature.
        final boolean bCoreValid = aSignature.validate(aValidateContext);
        if (!bCoreValid) {
            // This code block is for debugging purposes only - it has no semantical
            // influence
            s_aLogger.info("Signature failed core validation");
            final boolean bSignatureValueValid = aSignature.getSignatureValue().validate(aValidateContext);
            s_aLogger.info("  Signature value valid: " + bSignatureValueValid);
            if (!bSignatureValueValid) {
                // Check the validation status of each Reference.
                int nIndex = 0;
                final Iterator<?> i = aSignature.getSignedInfo().getReferences().iterator();
                while (i.hasNext()) {
                    final boolean bRefValid = ((Reference) i.next()).validate(aValidateContext);
                    s_aLogger.info("  Reference[" + nIndex + "] validity status: "
                            + (bRefValid ? "valid" : "NOT valid!"));
                    ++nIndex;
                }
            }
        }
        return bCoreValid;
    } finally {
        // Close the input stream
        StreamHelper.close(aEntityInputStream);
    }
}

From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] documentData, byte[] originalDocument) throws Exception {
    Document document = this.documentBuilder.parse(new ByteArrayInputStream(documentData));

    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (0 == signatureNodeList.getLength()) {
        LOG.debug("no XML signature found");
        return signatureInfos;
    }/* w  w w .j av a2s. c o m*/

    XAdESValidation xadesValidation = new XAdESValidation(this.context);

    for (int signatureNodeIdx = 0; signatureNodeIdx < signatureNodeList.getLength(); signatureNodeIdx++) {
        /*
         * Check signature.
         */
        Element signatureElement = (Element) signatureNodeList.item(signatureNodeIdx);
        xadesValidation.prepareDocument(signatureElement);

        KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keyInfoKeySelector, signatureElement);
        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM",
                new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
        XMLSignature xmlSignature;
        try {
            xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        } catch (MarshalException e) {
            LOG.error("XML signature marshalling error: " + e.getMessage(), e);
            continue;
        }
        LOG.debug("validating signature: " + xmlSignature.getId());
        boolean signatureValid = xmlSignature.validate(domValidateContext);
        LOG.debug("signature valid: " + signatureValid);
        if (!signatureValid) {
            LOG.error("invalid signature");
            throw new RuntimeException("invalid signature");
        }

        if (null != originalDocument) {
            Document originalDomDocument = XAdESUtils.loadDocument(originalDocument);
            LOG.debug("performing original document verification");
            verifyCoSignatureReference(xmlSignature, originalDomDocument);
            LOG.debug("original document verified");
        } else {
            /*
             * We can still check whether the co-signature ds:Reference is
             * indeed doing a co-signature.
             */
            verifyCoSignatureReference(xmlSignature, document);
        }

        X509Certificate signingCertificate = keyInfoKeySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(document, xmlSignature, signatureElement,
                signingCertificate);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static boolean validateDocumentSignature(Document signedDoc, Key publicKey)
        throws MarshalException, XMLSignatureException {
    if (signedDoc == null)
        throw new IllegalArgumentException("Signed Document is null");
    NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl == null || nl.getLength() == 0) {
        throw new IllegalArgumentException("Cannot find Signature element");
    }/*from w w w . j  a v a 2s .c o m*/
    if (publicKey == null)
        throw new IllegalArgumentException("Public Key is null");

    DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
    XMLSignature signature = signatureFactory.unmarshalXMLSignature(valContext);
    boolean coreValidity = signature.validate(valContext);

    if (!coreValidity) {
        boolean sv = signature.getSignatureValue().validate(valContext);
        log.fine("Signature validation status: " + sv);
    }

    return coreValidity;
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
 * Used to verify an enveloped digital signature
 *
 * @param doc a Document object containing the xml with the signature
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW a String containing the KeyStore password
 * @param verifyAlias a String containing the alias of the public key used for verification
 * @return True if signature passes verification, False otherwise
 *//*from   w w  w  .  j  a  v a 2s.c o m*/
public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW,
        String verifyAlias) {
    boolean coreValidation = false;
    PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias);
    if (publicKey == null) {
        logger.error(
                "Public key was null when verifying signature. Ensure keystore configuration values are set properly.");
        return false;
    }
    try {
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            logger.error("No XML Digital Signature was found. The document was discarded.");
            return false;
        }
        Node signatureNode = nl.item(nl.getLength() - 1);
        DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode);
        valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode()));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        coreValidation = signature.validate(valContext);
        if (!coreValidation) {
            // for testing/debugging when validation fails...
            logger.error("Digital Signature Core Validation failed.");
            boolean signatureValidation = signature.getSignatureValue().validate(valContext);
            logger.debug("Digital Signature Validation: " + signatureValidation);
            @SuppressWarnings("rawtypes")
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean referenceValidation = ref.validate(valContext);
                logger.debug("Digital Signature Reference Validation: " + referenceValidation);
                byte[] calculatedDigestValue = ref.getCalculatedDigestValue();
                byte[] digestValue = ref.getDigestValue();
                String cdvString = new String(Base64.encodeBase64(calculatedDigestValue));
                logger.debug("Digital Signature Calculated Digest Value: " + cdvString);
                String dvString = new String(Base64.encodeBase64(digestValue));
                logger.debug("Digital Signature Digest Value: " + dvString);
            }
        }
    } catch (MarshalException e) {
        logger.error("MarshalException when attempting to verify a digital signature.");
    } catch (XMLSignatureException e) {
        logger.error("XMLSignature Exception when attempting to verify a digital signature.");
    }
    return coreValidation;
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private boolean verify_signature(final Signature signature2) {
    try {//from  w  ww . ja  v a2s.  c  o m
        signature2.getBytes();
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        DocumentBuilder builder = fac.newDocumentBuilder();
        final Document doc = builder.parse(new ByteArrayInputStream(signature2.getBytes()));
        //System.err.println(new String(signature2.getBytes()));
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(
                noekkelpar.getSertifikat().getX509Certificate().getPublicKey(), nl.item(0));
        valContext.setURIDereferencer(new URIDereferencer() {
            @Override
            public Data dereference(final URIReference uriReference, final XMLCryptoContext context)
                    throws URIReferenceException {
                //System.out.println("$$$$ " + uriReference.getURI());
                for (AsicEAttachable file : files) {
                    if (file.getFileName().equals(uriReference.getURI().toString())) {
                        return new OctetStreamData(new ByteArrayInputStream(file.getBytes()));
                    }
                }
                uriReference.getURI().toString().replace("#", "");
                Node element = doc.getElementsByTagName("SignedProperties").item(0);
                return new DOMSubTreeData(element, false);

            }
        });
        XMLSignatureFactory fact = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fact.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        if (coreValidity == false) {
            System.err.println("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            System.out.println("signature validation status: " + sv);
            if (sv == false) {
                // Check the validation status of each Reference.
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                for (int j = 0; i.hasNext(); j++) {
                    boolean refValid = ((javax.xml.crypto.dsig.Reference) i.next()).validate(valContext);
                    System.out.println("ref[" + j + "] validity status: " + refValid);
                }
            }
        }
        return coreValidity;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return false;
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java

/**
 * Load a trusted list for the specified URL
 *
 * @param url//from w  w  w .  ja  va 2  s  . com
 * @param signerCert
 * @return
 * @throws IOException
 */
private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) {

    InputStream input = null;
    try {

        input = dataLoader.get(url);
        if (input == null) {

            throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url);
        }
        if (url.toLowerCase().endsWith(".zip")) {

            input = getZippedData(input);
        }

        Document doc = DSSXMLUtils.buildDOM(input);

        boolean coreValidity = true;
        if (checkSignature) {

            coreValidity = false;
            if (signerCert != null) {

                final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                if (signatureNodeList.getLength() == 0) {

                    throw new DSSException("Not ETSI compliant signature. The Xml is not signed.");
                }
                if (signatureNodeList.getLength() > 1) {

                    throw new DSSException("Not ETSI compliant signature. There is more than one signature.");
                }
                final Element signatureEl = (Element) signatureNodeList.item(0);

                final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey());
                final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl);
                final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl);
                valContext.setURIDereferencer(tsluriDereferencer);
                final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
                final XMLSignature signature = factory.unmarshalXMLSignature(valContext);
                coreValidity = signature.validate(valContext);
                LOG.info("The TSL signature validity: " + coreValidity);
            }
        }
        final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc);
        tsl.setWellSigned(coreValidity);
        return tsl;
    } catch (DSSException e) {

        throw e;
    } catch (Exception e) {

        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(input);
    }
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Verifica si una firma XML embedida es v&aacute;lida seg&uacute;n define
 * el est&aacute;ndar XML Signature (<a
 * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core
 * Validation</a>), y si el certificado era v&aacute;lido en la fecha dada.
 * <p>//w w w . j a v a  2  s . com
 * 
 * Esta rutina <b>NO</b> verifica si el certificado embedido en
 * &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad
 * certificadora que emiti&oacute; el certificado), pero si verifica que la
 * llave utilizada para verificar corresponde a la contenida en el
 * certificado.
 * 
 * @param xml
 *            el nodo &lt;Signature&gt;
 * @param date
 *            una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;n
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 * @see cl.nic.dte.VerifyResult
 * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler
 * @see #getCertificate(XMLSignature)
 */
public static VerifyResult verifySignature(Node xml, Date date) {

    try {

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        KeyValueKeySelector ksel = new KeyValueKeySelector();

        DOMValidateContext valContext = new DOMValidateContext(ksel, xml);

        // Unmarshal the signature
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);

        X509Certificate x509 = getCertificate(signature);

        // Verifica que un certificado bien embedido
        if (x509 == null) {
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                    Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509")));
        }

        try {
            // Valida que en la fecha dada el certificado era va'lido
            x509.checkValidity(date);
        } catch (CertificateExpiredException e) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
            message = message.replaceAll("%1", DateFormat.getDateInstance().format(date));
            message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore()));
            message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter()));
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        } catch (CertificateNotYetValidException e) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
            message = message.replaceAll("%1", DateFormat.getDateInstance().format(date));
            message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore()));
            message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter()));
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        }

        return (verifySignature(signature, valContext));
    } catch (MarshalException e1) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": "
                        + e1.getMessage()));
    }

}

From source file:com.alvexcore.repo.SimpleKeySelectorResult.java

private LicenseInfo getLicenseInfo(InputStream lic) {
    Document licenseXML = null;/* w  ww .  j  a v a 2 s .c  om*/
    try {
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setNamespaceAware(true);
        licenseXML = fact.newDocumentBuilder().parse(lic);
        NodeList nl = licenseXML.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(new AlvexKeySelector(), nl.item(0));
        XMLSignatureFactory sfac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature sgn = sfac.unmarshalXMLSignature(valContext);
        if (!sgn.validate(valContext))
            return LicenseInfo.INVALID_LICENSE;
    } catch (Exception ex) {
        return LicenseInfo.INVALID_LICENSE;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String id = licenseXML.getDocumentElement().getElementsByTagName("id").item(0).getTextContent();
    String product = licenseXML.getDocumentElement().getElementsByTagName("product").item(0).getTextContent();
    String owner = licenseXML.getDocumentElement().getElementsByTagName("owner").item(0).getTextContent();
    String edition = licenseXML.getDocumentElement().getElementsByTagName("edition").item(0).getTextContent();

    // We intentially have separate try/catch blocks. These tags may fail independently
    // and we'd like to prevent failed version tag from stopping dates parsing.
    String version = ANY_VERSION;
    try {
        version = licenseXML.getDocumentElement().getElementsByTagName("version").item(0).getTextContent();
    } catch (Exception e) {
    }

    Date issued = null;
    Date validThru = null;
    try {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        validThru = sdf.parse(expiresStr);
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        issued = sdf.parse(issuedStr);
    } catch (Exception e) {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        logger.warn(
                "Can not parse license dates. " + "Issued: " + issuedStr + ". Expires: " + expiresStr + ".");
    }

    int cores = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("cores").item(0).getTextContent());
    int users = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("users").item(0).getTextContent());

    return new LicenseInfo(id, owner, product, edition, version, cores, users, issued, validThru, false);
}