Enveloped signature
<yourxml>
...
<Signature>....</Signature>
</yourxml>
The signature is a node of the XML document. After validating the XML Signature, find the node, remove it of DOM structure and save the document.
// Instantiate the document to be signed.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(xml));
// Find Signature element.
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
//... XML Signature validation
//remove signature node from DOM
nl.item(0).getParentNode().removeChild(nl.item(0));
//write to file.
OutputStream os = new FileOutputStream(outputFileName);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
Enveloping signature
<Signature>
<Object Id="object">
<yourxml>...</yourxml>
</Object>
</Signature>
You could apply the same technique. Find the Object
node and save the first child to a file. But in this case, the XMLSignature
provides getObjects
method to get the signed objects
//XMLSignature result of validation process
XMLSignature signature = ...
//Gets the node
XMLObject xmlObject = (XMLObject)signature.getObjects().get(0);
Node yourXmlNode = ((DOMStructure)xmlObject.getContent().get(0)).getNode();
//Save to file
OutputStream os = new FileOutputStream(outputFileName);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(yourXmlNode), new StreamResult(os));