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:org.apache.xml.security.test.encryption.EncryptContentTest.java

/**
 * See SANTUARIO-301:// w ww  .  j  a  v  a2 s.  c om
 * https://issues.apache.org/jira/browse/SANTUARIO-301
 */
public void testMultipleKeyInfoElements() throws Exception {
    if (!haveISOPadding) {
        log.warn("Test testMultipleKeyInfoElements skipped as necessary algorithms not available");
        return;
    }

    Document doc = db.parse(new ByteArrayInputStream(MULTIPLE_USER_DATA.getBytes("UTF8")));
    NodeList dataToEncrypt = doc.getElementsByTagName("user");

    XMLCipher dataCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
    dataCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);

    KeyInfo keyInfo = new KeyInfo(doc);
    keyInfo.addKeyName("mykey");

    EncryptedData encryptedData = dataCipher.getEncryptedData();
    encryptedData.setKeyInfo(keyInfo);

    for (int i = 0; i < dataToEncrypt.getLength(); i++) {
        dataCipher.doFinal(doc, (Element) dataToEncrypt.item(i), true);
    }

    NodeList keyInfoList = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "KeyInfo");
    assertEquals(keyInfoList.getLength(), 2);
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

public void testEncryptedKeyWithRecipient() throws Exception {

    String filename = "data/org/apache/xml/security/encryption/encryptedKey.xml";
    if (basedir != null && !"".equals(basedir)) {
        filename = basedir + "/" + filename;
    }/*from w w  w. j  a v a2  s . c om*/
    File f = new File(filename);

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(f);

    XMLCipher keyCipher = XMLCipher.getInstance();
    keyCipher.init(XMLCipher.UNWRAP_MODE, null);

    NodeList ekList = document.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS,
            EncryptionConstants._TAG_ENCRYPTEDKEY);
    for (int i = 0; i < ekList.getLength(); i++) {
        EncryptedKey ek = keyCipher.loadEncryptedKey(document, (Element) ekList.item(i));
        assertNotNull(ek.getRecipient());
    }
}

From source file:org.apache.xml.security.test.signature.HMACOutputLengthTest.java

private static void validate(String data) throws Exception {
    // System.out.println("Validating " + data);
    File file = new File(
            BASEDIR + SEP + "data" + SEP + "javax" + SEP + "xml" + SEP + "crypto" + SEP + "dsig" + SEP, data);

    Document doc = dbf.newDocumentBuilder().parse(file);
    NodeList nl = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }//from   www.j  a  v  a2  s .  com
    Element sigElement = (Element) nl.item(0);
    XMLSignature signature = new XMLSignature(sigElement, file.toURI().toString());
    SecretKey sk = signature.createSecretKey("secret".getBytes("ASCII"));
    System.out.println("Validation status: " + signature.checkSignatureValue(sk));
}

From source file:org.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java

protected Node decryptAssertion(Document document, SSOKeyResolver keyResolver) throws SamlR2EncrypterException {
    try {// ww w.  j  ava 2  s . c  om
        org.w3c.dom.Element encryptedDataElement = (org.w3c.dom.Element) document.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);

        Key kek = loadKeyEncryptionKey(document, keyResolver);

        XMLCipher xmlCipher = XMLCipher.getInstance();
        xmlCipher.init(XMLCipher.DECRYPT_MODE, kek);

        Document decDoc = xmlCipher.doFinal(document, encryptedDataElement);

        Node assertionNode = decDoc.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion")
                .item(0);

        if (assertionNode == null)
            throw new SamlR2EncrypterException("No Assertion Node found in decrypted Document");

        return assertionNode;

    } catch (Exception e) {
        throw new SamlR2EncrypterException("Error decrypting Assertion data", e);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java

private Key loadKeyEncryptionKey(Document document, SSOKeyResolver keyResolver)
        throws SamlR2EncrypterException {
    try {//  w ww  . j  a  v  a  2 s.  co  m
        org.w3c.dom.Element encryptedKeyElement = (org.w3c.dom.Element) document.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDKEY).item(0);
        assert encryptedKeyElement != null : "No " + EncryptionConstants._TAG_ENCRYPTEDKEY
                + " Element found in Document";

        XMLCipher keyCipher = XMLCipher.getInstance();
        keyCipher.init(XMLCipher.UNWRAP_MODE, keyResolver.getPrivateKey());
        EncryptedKey ek = keyCipher.loadEncryptedKey(document, encryptedKeyElement);
        assert ek != null : "No encryptedKey found";

        org.w3c.dom.Element encryptedDataElement = (org.w3c.dom.Element) document.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
        assert encryptedDataElement != null : "No " + EncryptionConstants._TAG_ENCRYPTEDDATA
                + " Element found in Document";

        org.w3c.dom.Element encryptionMethodElem = (org.w3c.dom.Element) encryptedDataElement
                .getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS,
                        EncryptionConstants._TAG_ENCRYPTIONMETHOD)
                .item(0);
        assert encryptionMethodElem != null : "No " + EncryptionConstants._TAG_ENCRYPTIONMETHOD
                + " Element found in Document";

        String algoritmUri = encryptionMethodElem.getAttribute(EncryptionConstants._ATT_ALGORITHM);
        if (logger.isDebugEnabled())
            logger.debug("Encrypted Key algorithm: " + algoritmUri);

        return keyCipher.decryptKey(ek, algoritmUri);
    } catch (Exception e) {
        throw new SamlR2EncrypterException("Error loading or decrypting kek", e);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.core.encryption.XmlSecurityEncrypterImpl.java

protected Node decryptNameID(Document document, SSOKeyResolver keyResolver) throws SamlR2EncrypterException {
    try {//from  ww w  .  j av a2s. c  o m
        org.w3c.dom.Element encryptedDataElement = (org.w3c.dom.Element) document.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);

        Key kek = loadKeyEncryptionKey(document, keyResolver);

        XMLCipher xmlCipher = XMLCipher.getInstance();
        xmlCipher.init(XMLCipher.DECRYPT_MODE, kek);

        Document decDoc = xmlCipher.doFinal(document, encryptedDataElement);

        Node nameIDNode = decDoc.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "NameID")
                .item(0);

        if (nameIDNode == null)
            throw new SamlR2EncrypterException("No NameID Node found in decrypted Document");

        return nameIDNode;

    } catch (Exception e) {
        throw new SamlR2EncrypterException("Error decrypting NameID data", e);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

public void validate(RoleDescriptorType md, Document doc, Node root) throws SamlR2SignatureException {
    try {/*from w  w w.  j  a  v a 2s  . c  o  m*/

        // Check for duplicate IDs among XML elements
        NodeList nodes = evaluateXPath(doc, "//*/@ID");
        boolean duplicateIdExists = false;
        List<String> ids = new ArrayList<String>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (ids.contains(node.getNodeValue())) {
                duplicateIdExists = true;
                logger.error("Duplicated Element ID in XML Document : " + node.getNodeValue());
            }
            ids.add(node.getNodeValue());
        }
        if (duplicateIdExists) {
            throw new SamlR2SignatureException("Duplicate IDs in document ");
        }

        // TODO : Check that the Signature references the root element (the one used by the application)
        // Keep in mind that signature reference might be an XPath expression ?!

        // We know that in SAML, the root element is the element used by the application, we just need to make sure that
        // the root element is the one referred by the signature

        Node rootIdAttr = root.getAttributes().getNamedItem("ID");
        if (rootIdAttr == null)
            throw new SamlR2SignatureException("SAML document does not have an ID ");

        // Find Signature element
        NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodes.getLength() == 0) {
            throw new SamlR2SignatureException("Cannot find Signature elements");
        }

        // Create a DOM XMLSignatureFactory that will be used to unmarshal the
        // document containing the XMLSignature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        // Create a DOMValidateContext and specify a KeyValue KeySelector
        // and document context

        // Validate all Signature elements
        boolean rootIdMatched = false;
        for (int k = 0; k < signatureNodes.getLength(); k++) {

            DOMValidateContext valContext = new DOMValidateContext(new RawX509KeySelector(),
                    signatureNodes.item(k));

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

            // Validate the XMLSignature (generated above)
            boolean coreValidity = signature.validate(valContext);

            // Check core validation status
            if (!coreValidity) {

                if (logger.isDebugEnabled())
                    logger.debug("Signature failed core validation");

                boolean sv = signature.getSignatureValue().validate(valContext);

                if (logger.isDebugEnabled())
                    logger.debug("signature validation status: " + sv);
                // check the validation status of each Reference (should be only one!)
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                boolean refValid = true;
                for (int j = 0; i.hasNext(); j++) {

                    Reference ref = (Reference) i.next();
                    boolean b = ref.validate(valContext);
                    if (logger.isDebugEnabled())
                        logger.debug("ref[" + j + "] " + ref.getId() + " validity status: " + b);

                    if (!b) {
                        refValid = b;
                        logger.error("Signature failed reference validation " + ref.getId());
                    }

                }
                throw new SamlR2SignatureValidationException(
                        "Signature failed core validation" + (refValid ? " but passed all Reference validations"
                                : " and some/all Reference validation"));
            }

            if (logger.isDebugEnabled())
                logger.debug("Singnature passed Core validation");

            // The Signature must contain only one reference, and it must be the signed top element's ID.
            List<Reference> refs = signature.getSignedInfo().getReferences();
            if (refs.size() != 1) {
                throw new SamlR2SignatureValidationException(
                        "Invalid number of 'Reference' elements in signature : " + refs.size() + " ["
                                + signature.getId() + "]");
            }

            Reference reference = refs.get(0);
            String referenceURI = reference.getURI();

            if (referenceURI == null || !referenceURI.startsWith("#"))
                throw new SamlR2SignatureValidationException(
                        "Signature reference URI format not supported " + referenceURI);

            if (referenceURI.substring(1).equals(rootIdAttr.getNodeValue()))
                rootIdMatched = true;

            Key key = signature.getKeySelectorResult().getKey();
            boolean certValidity = validateCertificate(md, key);
            if (!certValidity) {
                throw new SamlR2SignatureValidationException("Signature failed Certificate validation");
            }

            if (logger.isDebugEnabled())
                logger.debug("Signature passed Certificate validation");

        }

        // Check that any of the Signatures matched the root element ID
        if (!rootIdMatched) {
            logger.error("No Signature element refers to signed element (possible signature wrapping attack)");
            throw new SamlR2SignatureValidationException("No Signature element refers to signed element");
        }

    } catch (MarshalException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * __UNDOCUMENTED__/*  w w w. j  a  v a 2s.  com*/
 *
 * @param xForm      __UNDOCUMENTED__
 * @param annotation __UNDOCUMENTED__
 * @return __UNDOCUMENTED__
 */
protected Element addHintFromDocumentation(Document xForm, XSAnnotation annotation) {
    if (annotation != null) {
        Element hintElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "hint");
        this.setXFormsId(hintElement);

        Text hintText = (Text) hintElement.appendChild(xForm.createTextNode(""));

        //write annotation to empty doc
        Document doc = DOMUtil.newDocument(true, false);
        annotation.writeAnnotation(doc, XSAnnotation.W3C_DOM_DOCUMENT);

        //get "annotation" element
        NodeList annots = doc.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "annotation");
        if (annots.getLength() > 0) {
            Element annotEl = (Element) annots.item(0);

            //documentation
            NodeList docos = annotEl.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema",
                    "documentation");
            int nbDocos = docos.getLength();
            for (int j = 0; j < nbDocos; j++) {
                Element doco = (Element) docos.item(j);

                //get text value
                String text = DOMUtil.getTextNodeAsString(doco);
                hintText.appendData(text);

                if (j < nbDocos - 1) {
                    hintText.appendData(" ");
                }
            }
            return hintElement;
        }
        return null;
    }

    return null;
}

From source file:org.chiba.xml.xforms.xpath.test.InstanceFactoryTest.java

/**
 * Sets up the test./*from  ww  w.  j a  v a 2  s . com*/
 *
 * @throws Exception in any error occurred during setup.
 */
protected void setUp() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    Document testDocument = factory.newDocumentBuilder()
            .parse(getClass().getResourceAsStream("InstanceFactoryTest.xml"));
    Element instanceElement = (Element) testDocument.getElementsByTagNameNS(NamespaceCtx.XFORMS_NS, "instance")
            .item(0);
    InstanceFactory instanceFactory = new InstanceFactory();
    instanceFactory.setNamespaceContext(instanceElement);

    this.document = factory.newDocumentBuilder().newDocument();
    this.context = JXPathContext.newContext(this.document);
    this.context.setFactory(instanceFactory);

    Map namespaces = NamespaceCtx.getAllNamespaces(instanceElement);
    Iterator iterator = namespaces.keySet().iterator();
    while (iterator.hasNext()) {
        String prefix = (String) iterator.next();
        String uri = (String) namespaces.get(prefix);

        this.context.registerNamespace(prefix, uri);
    }
}

From source file:org.chiba.xml.xpath.impl.JXPathDOMFactoryTest.java

/**
 * Sets up the test./*from  w  w  w.  ja  v a 2 s .  co m*/
 *
 * @throws Exception in any error occurred during setup.
 */
protected void setUp() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    Document testDocument = factory.newDocumentBuilder()
            .parse(getClass().getResourceAsStream("JXPathDOMFactoryTest.xhtml"));
    Element instanceElement = (Element) testDocument
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "instance").item(0);
    JXPathDOMFactory jxpathFactory = new JXPathDOMFactory();
    jxpathFactory.setNamespaceContext(instanceElement);

    this.document = factory.newDocumentBuilder().newDocument();
    this.context = JXPathContext.newContext(this.document);
    this.context.setFactory(jxpathFactory);

    Map namespaces = NamespaceResolver.getAllNamespaces(instanceElement);
    Iterator iterator = namespaces.keySet().iterator();
    while (iterator.hasNext()) {
        String prefix = (String) iterator.next();
        String uri = (String) namespaces.get(prefix);

        this.context.registerNamespace(prefix, uri);
    }
}