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

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

Introduction

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

Prototype

public Object setProperty(String name, Object value) 

Source Link

Document

This implementation uses an internal HashMap to map the name to the specified object.

Usage

From source file:be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }/*from w  w  w.  j a  v  a2s. c o  m*/

    OOXMLSignatureVerifier ooxmlSignatureVerifier = new OOXMLSignatureVerifier();
    List<String> signatureResourceNames = ooxmlSignatureVerifier.getSignatureResourceNames(document);
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    for (String signatureResourceName : signatureResourceNames) {
        LOG.debug("signatureResourceName: " + signatureResourceName);
        Document signatureDocument = ooxmlSignatureVerifier
                .getSignatureDocument(new ByteArrayInputStream(document), signatureResourceName);
        if (null == signatureDocument) {
            continue;
        }
        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (0 == signatureNodeList.getLength()) {
            continue;
        }
        Element signatureElement = (Element) signatureNodeList.item(0);
        xadesValidation.prepareDocument(signatureElement);
        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
        OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        LOG.debug("validating signature: " + xmlSignature.getId());
        boolean valid = xmlSignature.validate(domValidateContext);
        LOG.debug("signature valid: " + valid);
        if (!valid) {
            LOG.error("signature invalid");
            continue;
        }

        // check OOXML's XML DSig/XAdES requirements
        if (!ooxmlSignatureVerifier.isValidOOXMLSignature(xmlSignature, document)) {
            LOG.error("Invalid OOXML Signature");
            continue;
        }

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

From source file:be.fedict.eid.applet.service.signer.xps.XPSSignatureVerifier.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);
    for (String signatureResourceName : signatureResourceNames) {
        LOG.debug("signature resource name: " + signatureResourceName);
        Document signatureDocument = loadDocument(url, signatureResourceName);
        if (null == signatureDocument) {
            LOG.warn("signature resource not found: " + signatureResourceName);
            continue;
        }/*  w w  w  .jav a2 s .  c o m*/

        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (0 == signatureNodeList.getLength()) {
            LOG.debug("no signature elements present");
            continue;
        }
        Node signatureNode = signatureNodeList.item(0);

        OPCKeySelector keySelector = new OPCKeySelector(url, signatureResourceName);
        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 validity = xmlSignature.validate(domValidateContext);

        if (false == validity) {
            LOG.debug("not a valid signature");
            continue;
        }
        // TODO: check what has been signed.

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

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");
    }//from  ww w.j  av  a2s . c om
    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: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);

        /**
         * 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):
         *///from   www.  j  a  v a2  s . c o  m
        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.juddi.v3.client.cryptor.DigSigUtil.java

private boolean verifySignature(Element element, PublicKey validatingKey,
        AtomicReference<String> OutReadableErrorMessage) {
    if (OutReadableErrorMessage == null) {
        OutReadableErrorMessage = new AtomicReference<String>();
    }//  w  w w.j av  a2  s  .co  m
    XMLSignatureFactory fac = initXMLSigFactory();
    NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Cannot find Signature element");
    }
    DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0));
    try {
        valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        // Check core validation status.
        if (coreValidity == false) {
            logger.warn("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            logger.debug("signature validation status: " + sv);
            OutReadableErrorMessage
                    .set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get());
            // Check the validation status of each Reference.
            @SuppressWarnings("unchecked")
            Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
            //System.out.println("---------------------------------------------");
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean refValid = ref.validate(valContext);
                logger.debug(j);
                logger.debug("ref[" + j + "] validity status: " + refValid);
                if (!refValid) {
                    OutReadableErrorMessage
                            .set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get());
                }
                logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                for (Object xform : ref.getTransforms()) {
                    logger.debug("Transform: " + xform);
                }
                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                String expectedDigValStr = digestToString(ref.getDigestValue());
                logger.warn("    Calc Digest: " + calcDigValStr);
                logger.warn("Expected Digest: " + expectedDigValStr);
                if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) {
                    OutReadableErrorMessage.set(
                            "digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get());
                }
            }
        } else {
            logger.info("Signature passed core validation");
        }
        return coreValidity;
    } catch (Exception e) {
        OutReadableErrorMessage
                .set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get());
        logger.fatal(e);
        return false;
    }
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Carries out the cryptographic part of signature verification on a parsed
 * "Signature" element.//w  ww  .jav a2s.co  m
 * @param signature
 * @throws Exception 
 */
private void verifySignature(Element signature) throws Exception {
    X509Certificate x509 = getCertificate(signature);
    SimpleKeySelector sks = new SimpleKeySelector();
    sks.setFixedKey(x509.getPublicKey());
    DOMStructure sig = new DOMStructure(signature);
    XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM");
    DOMValidateContext dvc = new DOMValidateContext(sks, signature);
    dvc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    XMLSignature xmlsig = xsf.unmarshalXMLSignature(sig);
    boolean isvalid = xmlsig.validate(dvc);
    if (!isvalid) {
        throw new Exception("Signature invalid");
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testSignedOOXML2() throws Exception {
    // setup//w  w  w . ja va 2  s.c  o  m
    URL url = OOXMLSignatureVerifierTest.class.getResource("/signed.docx");

    // operate
    OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier();
    List<X509Certificate> result = verifier.getSigners(url);

    // verify
    assertNotNull(result);
    assertEquals(1, result.size());
    X509Certificate signer = result.get(0);
    LOG.debug("signer: " + signer.getSubjectX500Principal());

    byte[] document = IOUtils.toByteArray(url.openStream());
    List<String> signatureResourceNames = verifier.getSignatureResourceNames(document);
    Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document),
            signatureResourceNames.get(0));
    NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

    Element signatureElement = (Element) signatureNodeList.item(0);
    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document);
    domValidateContext.setURIDereferencer(dereferencer);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testSignedOOXMLOffice2010ValidOOXML() throws Exception {
    // setup/*from  w w  w .  ja v a  2s  .  c  o  m*/
    URL url = OOXMLSignatureVerifierTest.class.getResource("/hallo.docx");

    // operate
    OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier();
    List<X509Certificate> result = verifier.getSigners(url);

    // verify
    assertNotNull(result);
    assertEquals(1, result.size());
    X509Certificate signer = result.get(0);
    LOG.debug("signer: " + signer.getSubjectX500Principal());

    byte[] document = IOUtils.toByteArray(url.openStream());
    List<String> signatureResourceNames = verifier.getSignatureResourceNames(document);
    Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document),
            signatureResourceNames.get(0));
    NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

    Element signatureElement = (Element) signatureNodeList.item(0);
    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document);
    domValidateContext.setURIDereferencer(dereferencer);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testVerifySignature() throws Exception {

    java.util.logging.Logger logger = java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
    logger.log(Level.FINE, "test");

    URL url = OOXMLSignatureVerifierTest.class.getResource("/hello-world-signed.docx");
    String signatureResourceName = getSignatureResourceName(url);
    LOG.debug("signature resource name: " + signatureResourceName);

    OOXMLProvider.install();//from  w w w  .j  a  va2 s  .  c om

    ZipInputStream zipInputStream = new ZipInputStream(url.openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (false == signatureResourceName.equals(zipEntry.getName())) {
            continue;
        }
        Document signatureDocument = loadDocument(zipInputStream);
        LOG.debug("signature loaded");
        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        assertEquals(1, signatureNodeList.getLength());
        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 validity = xmlSignature.validate(domValidateContext);
        assertTrue(validity);
        List<?> objects = xmlSignature.getObjects();
        for (Object object : objects) {
            LOG.debug("ds:Object class type: " + object.getClass().getName());
        }
        break;
    }
}