Example usage for org.w3c.dom Document getElementsByTagNameNS

List of usage examples for org.w3c.dom Document getElementsByTagNameNS

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagNameNS.

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName);

Source Link

Document

Returns a NodeList of all the Elements with a given local name and namespace URI in document order.

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");
    }//  www .  j  a  va2  s . 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.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java

private void prepareDocument(Document xkmsDocument) {
    Element prototypeElement = xkmsDocument.getElementById(this.prototypeKeyBindingId);
    if (null == prototypeElement) {
        LOG.warn("Prototype element not found via Id");
        prototypeElement = (Element) xkmsDocument
                .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "PrototypeKeyBinding").item(0);
        if (null == prototypeElement) {
            prototypeElement = (Element) xkmsDocument
                    .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "RevokeKeyBinding").item(0);
        }/*from  ww w  .  j a  v a  2  s.  co m*/
        prototypeElement.setIdAttribute("Id", true);
    }
}

From source file:com.castlemock.web.mock.soap.model.project.service.CreateSoapPortsService.java

/**
 * Search and find for a specific element
 * @param document The document that will be parsed
 * @param namespace The element namespace
 * @param type The type or name of the element
 * @param identifier The identifier is used to determine if the element is the correct element being searched for.
 * @return An element that matches the provided search criteria
 *//*from   ww  w.  j av  a 2  s.co m*/
private Element findElement(final Document document, final String namespace, final String type,
        final String identifier) {
    final NodeList nodeList = document.getElementsByTagNameNS(namespace, type);
    for (int index = 0; index < nodeList.getLength(); index++) {
        Node node = nodeList.item(index);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            String name = element.getAttribute("name");
            if (name.equals(identifier)) {
                return element;
            }
        }
    }
    return null;
}

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;/*from  w  ww  .  j a v a 2s  .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:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }/*ww  w  .  j av a  2s  .co m*/
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "Register");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument.getElementsByTagNameNS(XKMS_NAMESPACE,
            "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

From source file:be.e_contract.mycarenet.xkms2.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }/*  w  w  w.  j a  v a2s. c  o m*/
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "RegisterRequest");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument
            .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

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 .j  a  v  a  2s.co  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:io.personium.engine.source.FsServiceResourceSourceManager.java

/**
 * ??????.//from ww w.j a v  a 2 s .com
 * @param xml XML
 * @param svcName ??
 * @return 
 */
private void parseServiceTag() {
    DocumentBuilder builder = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc = null;
    InputStream is = new ByteArrayInputStream(this.serviceCollectionInfo.getBytes());
    try {
        doc = builder.parse(is);
        Element el = doc.getDocumentElement();
        this.serviceSubject = el.getAttribute("subject");
        NodeList nl = doc.getElementsByTagNameNS("*", "path");
        for (int i = 0; i < nl.getLength(); i++) {
            NamedNodeMap nnm = nl.item(i).getAttributes();
            pathMap.put(nnm.getNamedItem("name").getNodeValue(), nnm.getNamedItem("src").getNodeValue());
        }
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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;
    }/*  www . j ava 2s.  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:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private boolean verify_signature(final Signature signature2) {
    try {/*from  w  ww. j  av a 2 s . 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;
    }
}