Example usage for javax.xml.crypto.dsig Reference getURI

List of usage examples for javax.xml.crypto.dsig Reference getURI

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig Reference getURI.

Prototype

String getURI();

Source Link

Document

Returns the URI of the referenced data object.

Usage

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

@SuppressWarnings("unchecked")
public static String findReferenceUri(XMLSignature xmlSignature, String type) {

    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        if (type.equals(reference.getType())) {
            return reference.getURI();
        }/*from   w w w. j av a2 s  . co  m*/
    }

    return null;
}

From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java

private void checkIntegrity(XMLSignature xmlSignature, byte[] document, byte[] originalDocument)
        throws IOException {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }//w w  w . j a v  a 2  s. co  m
    Set<String> dsReferenceUris = new HashSet<String>();
    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    @SuppressWarnings("unchecked")
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        String referenceUri = reference.getURI();
        dsReferenceUris.add(referenceUri);
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (false == ODFUtil.isToBeSigned(zipEntry)) {
            continue;
        }
        String uri = zipEntry.getName().replaceAll(" ", "%20");
        if (false == dsReferenceUris.contains(uri)) {
            LOG.warn("no ds:Reference for ODF entry: " + zipEntry.getName());
            throw new RuntimeException("no ds:Reference for ODF entry: " + zipEntry.getName());
        }
    }
}

From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }/*w  ww  . ja va2s  .c om*/
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ASiCUtil.isSignatureZipEntry(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);
        ASiCURIDereferencer dereferencer = new ASiCURIDereferencer(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 (ASiCUtil.isSignatureZipEntry(zipEntry)) {
                continue;
            }
            if (false == referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ASiC entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

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

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;//  w  w w .j a  v a2s  .  c  o  m
    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.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Validate the Signature Reference URI is the same document Uri.
 * It should not point to external resources.
 * @param reference Signature reference to validate the uri of. not null.
 * @throws XMLSignatureException when the validation fails.
 */// www .j av a 2s. c om
private void validateReferenceUri(Reference reference) throws XMLSignatureException {
    assert reference != null;

    if (!org.jcp.xml.dsig.internal.dom.Utils.sameDocumentURI(reference.getURI())) {
        throw new XMLSignatureException(String.format(
                "Invalid reference '%s'. Only a same-document references are aupported.", reference.getURI()));
    }
}

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

private Reference findReferenceFromURI(List<Reference> refs, String referenceURI) {

    for (Reference ref : refs) {
        if (ref.getURI().equals(referenceURI)) {
            LOG.debug("Found \"" + referenceURI + "\" ds:reference");
            return ref;
        }//from  w w w.ja  v a2s.  co  m
    }
    return null;
}

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  .java 2s. 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:com.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Validate references present in the XmlSignature.
 * @param xmlSignature the xml signature whose references are to be validated. not null.
 * @param valContext validation context used to validate the signature itself. not null.
 * @param document document the signature belongs to. not null.
 * @param timestampNode the timestamp node of the soap security header within the document.
 * @throws XMLSignatureException when the validation fails.
 *//*from   w ww .jav a2s . c om*/
private void validateSignatureReferences(XMLSignature xmlSignature, DOMValidateContext valContext,
        Document document, Node timestampNode) throws XMLSignatureException {

    assert xmlSignature != null;
    assert valContext != null;
    assert document != null;
    assert timestampNode != null;

    //    If a signature is applied to a request then it must include:
    //    Either the <S11:Body>, or the WS-Trust element as a direct child of the <S11:Body>
    //    The <wsu:Timestamp>, if present in the <S11:Header>. 
    //        (in fact this must be present as per same spec, and SOAPHeaderExtractor validates it)

    Node soapBody = getSoapBody(document);
    Node wsTrustNode = getWsTrustNode(soapBody);
    boolean foundTimestampElement = false;
    boolean foundBodyOrWSTrustElement = false;

    List<Reference> references = xmlSignature.getSignedInfo().getReferences();
    if ((references == null) || (references.size() == 0)) {
        throw new XMLSignatureException("Signature's SignInfo does not contain any references.");
    }

    for (Reference reference : references) {

        if (reference != null) {
            validateReferenceTransforms(reference);
            validateReferenceUri(reference);
            // note: order is important, we should not try to validate digests
            // before we checked expected transforms, and uri etc.
            if (!reference.validate(valContext)) {
                throw new XMLSignatureException(
                        String.format("Signature reference '%s' is invalid.", reference.getURI()));
            }

            if (!foundTimestampElement || !foundBodyOrWSTrustElement) {
                String id = org.jcp.xml.dsig.internal.dom.Utils.parseIdFromSameDocumentURI(reference.getURI());
                Node referencedNode = document.getElementById(id);
                foundTimestampElement = (foundTimestampElement) || (timestampNode.isSameNode(referencedNode));
                foundBodyOrWSTrustElement = (foundBodyOrWSTrustElement) || (soapBody.isSameNode(referencedNode))
                        || (wsTrustNode.isSameNode(referencedNode));
            }
        }
    } // for each reference

    if (!foundTimestampElement || !foundBodyOrWSTrustElement) {
        throw new XMLSignatureException(
                "Signature must include <wsu:Timestamp> and either SoapBody, or the WSTrust element within it.");
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java

@Override
public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) {

    final SignatureCryptographicVerification scv = new SignatureCryptographicVerification();

    final CertificateToken certToken = getSigningCertificate().getCertToken();
    if (certToken != null) {

        final PublicKey publicKey = certToken.getCertificate().getPublicKey();
        final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);

        /**/*from   ww w  .  j a  v a2  s  . c o  m*/
         * Creating a Validation Context<br>
         * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we
         * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it
         * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which
         * is the first entry of the NodeList we generated earlier):
         */
        final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement);
        try {

            URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument);
            valContext.setURIDereferencer(dereferencer);
            /**
             * This property controls whether or not the digested Reference objects will cache the dereferenced content
             * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and
             * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE.
             */
            valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);

            /**
             * Unmarshalling the XML Signature<br>
             * We extract the contents of the Signature element into an XMLSignature object. This process is called
             * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application
             * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code:
             */

            // These providers do not support ECDSA algorithm
            // factory = XMLSignatureFactory.getInstance("DOM");
            // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig");
            // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());

            // This provider support ECDSA signature
            /**
             * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N
             * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br>
             * If this library is used than the same library must be used for the URIDereferencer.
             */
            final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider);

            /**
             * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and
             * pass it the validation context we created earlier:
             */
            final XMLSignature signature = factory.unmarshalXMLSignature(valContext);
            //System.out.println("XMLSignature class: " + signature.getClass());

            // Austrian specific signature
            //org.apache.xml.security.signature.XMLSignature signature_ = null;
            // try {
            // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, "");
            // } catch (Exception e) {
            //
            // throw new DSSException(e);
            // }
            // signature.addResourceResolver(new XPointerResourceResolver(signatureElement));

            //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1);
            /**
             * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set
             * manually.<br>
             * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature
             * tag. It prevents some signatures to be validated.<br>
             *
             * Solution: the following lines where added:
             */
            final Document document = signatureElement.getOwnerDocument();
            final Element rootElement = document.getDocumentElement();
            if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) {

                valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME);
            }

            DSSXMLUtils.recursiveIdBrowse(valContext, rootElement);

            /**
             * Validating the XML Signature<br>
             * Now we are ready to validate the signature. We do this by invoking the validate method on the
             * XMLSignature object, and pass it the validation context as follows:
             */
            boolean coreValidity = false;
            try {

                coreValidity = signature.validate(valContext);
            } catch (XMLSignatureException e) {

                scv.setErrorMessage("Signature validation: " + e.getMessage());
            }
            boolean signatureValidity = coreValidity;
            boolean dataFound = true;
            boolean dataHashValid = true;

            /**
             * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure.
             * There are two phases in core XML Signature validation: <br>
             * - Signature validation (the cryptographic verification of the signature)<br>
             * - Reference validation (the verification of the digest of each reference in the signature)<br>
             * Each phase must be successful for the signature to be valid. To check if the signature failed to
             * cryptographically validate, we can check the status, as follows:
             */

            try {

                signatureValidity = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {

                scv.setErrorMessage(e.getMessage());
            }

            @SuppressWarnings("unchecked")
            final List<Reference> references = signature.getSignedInfo().getReferences();
            for (Reference reference : references) {

                boolean refHashValidity = false;
                try {

                    refHashValidity = reference.validate(valContext);
                } catch (XMLSignatureException e) {

                    scv.setErrorMessage(reference.getURI() + ": " + e.getMessage());
                }
                dataHashValid = dataHashValid && refHashValidity;
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity);
                }
                final Data data = reference.getDereferencedData();
                dataFound = dataFound && (data != null);

                final InputStream digestInputStream = reference.getDigestInputStream();
                if (data != null && digestInputStream != null) {

                    // The references are saved for later treatment in -A level.
                    try {

                        IOUtils.copy(digestInputStream, referencesDigestOutputStream);
                    } catch (IOException e) {
                    }
                }
            }
            scv.setReferenceDataFound(dataFound);
            scv.setReferenceDataIntact(dataHashValid);
            scv.setSignatureIntegrity(signatureValidity);
        } catch (MarshalException e) {

            scv.setErrorMessage(e.getMessage());
        }
    } else {

        scv.setErrorMessage(
                "Unable to proceed with the signature cryptographic verification. There is no signing certificate!");
    }
    return scv;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }/*from ww  w .  j  a  v  a  2s .  c om*/

    if (!(o instanceof Reference)) {
        return false;
    }
    Reference oref = (Reference) o;

    boolean idsEqual = (id == null ? oref.getId() == null : id.equals(oref.getId()));
    boolean urisEqual = (uri == null ? oref.getURI() == null : uri.equals(oref.getURI()));
    boolean typesEqual = (type == null ? oref.getType() == null : type.equals(oref.getType()));
    boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue());

    return digestMethod.equals(oref.getDigestMethod()) && idsEqual && urisEqual && typesEqual
            && allTransforms.equals(oref.getTransforms()) && digestValuesEqual;
}