Java Code Examples for org.w3c.dom.Node#replaceChild()

The following examples show how to use org.w3c.dom.Node#replaceChild() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SearchController.java    From CPUSim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * checks if the text node contains the search string to call further method to highlight
 *
 * @param originalDoc   a Document generated from webEngine based on webView
 * @param node          a node that contains text to be searched
 * @param searchRegEx   a regular expression to be searched
 */
private void nodeBuilder(Document originalDoc, Node node, String searchRegEx) {
    String nodeText = node.getTextContent();
    
    Pattern p = Pattern.compile(searchRegEx);
    Matcher m = p.matcher(nodeText);

    if(m.find()){
        int occurenceStartIndex = m.start();
        int occurenceEndIndex = m.end();
        Node newChild = generateNewChildNode(originalDoc, nodeText,occurenceStartIndex,occurenceEndIndex);
 
        Node parentNode = node.getParentNode();
        parentNode.replaceChild(newChild, node);
        
        if(newChild.getLastChild().getNodeType() == Node.TEXT_NODE){
            nodeBuilder(originalDoc, newChild.getLastChild(), searchRegEx);
        }
    }
}
 
Example 2
Source File: DSSXMLUtils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Node getIndentedSignature(final Node signature, List<String> noIndentObjectIds) {
	Node indentedSignature = getIndentedNode(signature);
	NodeList sigChildNodes = signature.getChildNodes();
	for (int i = 0; i < sigChildNodes.getLength(); i++) {
		Node childNode = sigChildNodes.item(i);
		if (childNode.getNodeType() == Node.ELEMENT_NODE) {
			Element sigChild = (Element) childNode;
			String idAttribute = getIDIdentifier(sigChild);
			if (noIndentObjectIds.contains(idAttribute)) {
				Node nodeToReplace = DomUtils.getNode(indentedSignature, ".//*" + DomUtils.getXPathByIdAttribute(idAttribute));
				Node importedNode = indentedSignature.getOwnerDocument().importNode(sigChild, true);
				indentedSignature.replaceChild(importedNode, nodeToReplace);
			}
		}
	}
	return indentedSignature;
}
 
Example 3
Source File: ElementImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
protected static SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = (Name) eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
        Node nextChild = (Node) eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 4
Source File: ElementImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
protected static SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = (Name) eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
        Node nextChild = (Node) eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 5
Source File: XMLCipher.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 6
Source File: XMLCipher.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 7
Source File: ElementImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
protected static SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = (Name) eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
        Node nextChild = (Node) eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 8
Source File: XPathReplacer.java    From maven-replacer-plugin with MIT License 6 votes vote down vote up
private void replaceContent(NodeList replacementNodes, Replacement replacement, boolean regex, int regexFlags) throws Exception {
	for (int i=0; i < replacementNodes.getLength(); i++) {
		Node replacementNode = replacementNodes.item(i);

		switch (replacementNode.getNodeType()) {
		case Node.ATTRIBUTE_NODE: case Node.TEXT_NODE:
			String replacedValue = tokenReplacer.replace(replacementNode.getTextContent(), replacement, regex, regexFlags);
			replacementNode.setNodeValue(replacedValue);
			break;
		default:
			String replacementNodeStr = convertNodeToString(replacementNode);
			String replacedNodeStr = tokenReplacer.replace(replacementNodeStr, replacement, regex, regexFlags);

			Node parent = replacementNode.getParentNode();
			if (parent.getOwnerDocument() == null) {
				throw new UnsupportedOperationException("Cannot replace a node's content not part of a parent node.");
			}
			Node replacedNode = convertXmlToNode(replacedNodeStr);
			Node newNode = parent.getOwnerDocument().importNode(replacedNode, true);
			parent.replaceChild(newNode, replacementNode);
		}
	}
}
 
Example 9
Source File: ElementImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
protected static SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = (Name) eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
        Node nextChild = (Node) eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 10
Source File: XMLCipher.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 11
Source File: XMLCipher.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 12
Source File: XMLCipher.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 13
Source File: XMLCipher.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 14
Source File: XMLCipher.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 15
Source File: XMLCipher.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 16
Source File: XMLCipher.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 17
Source File: XmlElementStack.java    From caja with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void processText(Token<HtmlTokenType> text) {
  Node parent = getBottom().n;

  Text textNode;
  switch (text.type) {
    case CDATA:
      textNode = doc.createCDATASection(
          text.text.substring(9, text.text.length() - 3));
      break;
    case TEXT:
      {
        Node lastSibling = parent.getLastChild();
        if (lastSibling != null) {
          if (lastSibling.getNodeType() == Node.TEXT_NODE) {
            Text combined = doc.createTextNode(
                lastSibling.getNodeValue() + Nodes.decode(text.text));
            if (needsDebugData) {
              Nodes.setRawText(
                  combined, Nodes.getRawText((Text) lastSibling) + text.text);
              Nodes.setFilePositionFor(
                  combined,
                  FilePosition.span(
                      Nodes.getFilePositionFor(lastSibling), text.pos));
            }
            parent.replaceChild(combined, lastSibling);
            return;
          }
        }
      }
      textNode = doc.createTextNode(Nodes.decode(text.text));
      break;
    case UNESCAPED:
      textNode = doc.createTextNode(text.text);
      break;
    default:
      throw new IllegalArgumentException(text.toString());
  }
  if (needsDebugData) {
    Nodes.setRawText(textNode, text.text);
    Nodes.setFilePositionFor(textNode, text.pos);
  }
  doAppend(textNode, parent);
}
 
Example 18
Source File: UpdateFieldAdapter.java    From development with Apache License 2.0 4 votes vote down vote up
private void updateNode(SOAPMessageContext context, List<FieldInfo> fields,
        String variableName, boolean isResponse) throws SOAPException {

    Node variableNode;
    if (isResponse) {
        variableNode = context.getMessage().getSOAPBody().getFirstChild()
                .getFirstChild();
    } else {
        variableNode = context.getMessage().getSOAPBody()
                .getElementsByTagName(variableName).item(0);
    }

    NodeList fieldsList = variableNode.getChildNodes();
    int fieldsSize = fieldsList.getLength();

    for (int i = 0; i < fieldsSize; i++) {
        Node fieldNode = fieldsList.item(i);
        for (FieldInfo field : fields) {
            String oldNodeName = "";
            String updatedNodeName = "";
            if (isResponse) {
                oldNodeName = PREFIX
                        + field.getNewField().getVariableName();
                updatedNodeName = PREFIX
                        + field.getOldField().getVariableName();
            } else {
                oldNodeName = PREFIX
                        + field.getOldField().getVariableName();
                updatedNodeName = PREFIX
                        + field.getNewField().getVariableName();

            }
            if (fieldNode.getNodeName().equals(oldNodeName)) {
                Element newNode = variableNode
                        .getOwnerDocument()
                        .createElementNS(
                                variableNode.getFirstChild()
                                        .getNamespaceURI(), updatedNodeName);
                newNode.setTextContent(fieldNode.getTextContent());
                variableNode.replaceChild(newNode, fieldNode);
            }
        }
    }
}
 
Example 19
Source File: XMLEncryptionUtil.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Given an element in a Document, encrypt the element and replace the element in the document with the encrypted
 * data
 *
 * @param elementQName QName of the element that we like to encrypt
 * @param document
 * @param publicKey
 * @param secretKey
 * @param keySize
 * @param wrappingElementQName A QName of an element that will wrap the encrypted element
 * @param addEncryptedKeyInKeyInfo Need for the EncryptedKey to be placed in ds:KeyInfo
 *
 * @throws ProcessingException
 */
public static void encryptElement(QName elementQName, Document document, PublicKey publicKey, SecretKey secretKey,
                                  int keySize, QName wrappingElementQName, boolean addEncryptedKeyInKeyInfo) throws ProcessingException {
    if (elementQName == null)
        throw logger.nullArgumentError("elementQName");
    if (document == null)
        throw logger.nullArgumentError("document");
    String wrappingElementPrefix = wrappingElementQName.getPrefix();
    if (wrappingElementPrefix == null || "".equals(wrappingElementPrefix))
        throw logger.wrongTypeError("Wrapping element prefix invalid");

    Element documentElement = DocumentUtil.getElement(document, elementQName);

    if (documentElement == null)
        throw logger.domMissingDocElementError(elementQName.toString());

    XMLCipher cipher = null;
    EncryptedKey encryptedKey = encryptKey(document, secretKey, publicKey, keySize);

    String encryptionAlgorithm = getXMLEncryptionURL(secretKey.getAlgorithm(), keySize);
    // Encrypt the Document
    try {
        cipher = XMLCipher.getInstance(encryptionAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    } catch (XMLEncryptionException e1) {
        throw logger.processingError(e1);
    }

    Document encryptedDoc;
    try {
        encryptedDoc = cipher.doFinal(document, documentElement);
    } catch (Exception e) {
        throw logger.processingError(e);
    }

    // The EncryptedKey element is added
    Element encryptedKeyElement = cipher.martial(document, encryptedKey);

    final String wrappingElementName;

    if (StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElementName = wrappingElementQName.getLocalPart();
    } else {
        wrappingElementName = wrappingElementPrefix + ":" + wrappingElementQName.getLocalPart();
    }
    // Create the wrapping element and set its attribute NS
    Element wrappingElement = encryptedDoc.createElementNS(wrappingElementQName.getNamespaceURI(), wrappingElementName);

    if (! StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + wrappingElementPrefix, wrappingElementQName.getNamespaceURI());
    }

    // Get Hold of the Cipher Data
    NodeList cipherElements = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA);
    if (cipherElements == null || cipherElements.getLength() == 0)
        throw logger.domMissingElementError("xenc:EncryptedData");
    Element encryptedDataElement = (Element) cipherElements.item(0);

    Node parentOfEncNode = encryptedDataElement.getParentNode();
    parentOfEncNode.replaceChild(wrappingElement, encryptedDataElement);

    wrappingElement.appendChild(encryptedDataElement);

    if (addEncryptedKeyInKeyInfo) {
        // Outer ds:KeyInfo Element to hold the EncryptionKey
        Element sigElement = encryptedDoc.createElementNS(XMLSignature.XMLNS, DS_KEY_INFO);
        sigElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:ds", XMLSignature.XMLNS);
        sigElement.appendChild(encryptedKeyElement);

        // Insert the Encrypted key before the CipherData element
        NodeList nodeList = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
        if (nodeList == null || nodeList.getLength() == 0)
            throw logger.domMissingElementError("xenc:CipherData");
        Element cipherDataElement = (Element) nodeList.item(0);
        Node cipherParent = cipherDataElement.getParentNode();
        cipherParent.insertBefore(sigElement, cipherDataElement);
    } else {
        // Add the encrypted key as a child of the wrapping element
        wrappingElement.appendChild(encryptedKeyElement);
    }
}
 
Example 20
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a node in a document
 *
 * @param doc
 * @param nodeToBeSigned
 * @param keyPair
 * @param digestMethod
 * @param signatureMethod
 * @param referenceURI
 *
 * @return
 *
 * @throws ParserConfigurationException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @throws GeneralSecurityException
 */
public static Document sign(Document doc, Node nodeToBeSigned, String keyName, KeyPair keyPair, String digestMethod,
                            String signatureMethod, String referenceURI, X509Certificate x509Certificate,
                            String canonicalizationMethodType) throws ParserConfigurationException, GeneralSecurityException,
        MarshalException, XMLSignatureException {
    if (nodeToBeSigned == null)
        throw logger.nullArgumentError("Node to be signed");

    if (logger.isTraceEnabled()) {
        logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }

    Node parentNode = nodeToBeSigned.getParentNode();

    // Let us create a new Document
    Document newDoc = DocumentUtil.createDocument();
    // Import the node
    Node signingNode = newDoc.importNode(nodeToBeSigned, true);
    newDoc.appendChild(signingNode);

    if (!referenceURI.isEmpty()) {
        propagateIDAttributeSetup(nodeToBeSigned, newDoc.getDocumentElement());
    }
    newDoc = sign(newDoc, keyName, keyPair, digestMethod, signatureMethod, referenceURI, x509Certificate, canonicalizationMethodType);

    // if the signed element is a SAMLv2.0 assertion we need to move the signature element to the position
    // specified in the schema (before the assertion subject element).
    if (nodeToBeSigned.getLocalName().equals("Assertion")
            && WSTrustConstants.SAML2_ASSERTION_NS.equals(nodeToBeSigned.getNamespaceURI())) {
        Node signatureNode = DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.DSIG_NS, "Signature"));
        Node subjectNode = DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.SAML2_ASSERTION_NS, "Subject"));
        if (signatureNode != null && subjectNode != null) {
            newDoc.getDocumentElement().removeChild(signatureNode);
            newDoc.getDocumentElement().insertBefore(signatureNode, subjectNode);
        }
    }

    // Now let us import this signed doc into the original document we got in the method call
    Node signedNode = doc.importNode(newDoc.getFirstChild(), true);

    if (!referenceURI.isEmpty()) {
        propagateIDAttributeSetup(newDoc.getDocumentElement(), (Element) signedNode);
    }

    parentNode.replaceChild(signedNode, nodeToBeSigned);
    // doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);

    return doc;
}