封裝簽名
<yourxml>
...
<Signature>....</Signature>
</yourxml>
簽名是XML文檔的一個節點。驗證XML簽名後,找到該節點,將其刪除並保存該文檔。
// 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));
包絡簽名
<Signature>
<Object Id="object">
<yourxml>...</yourxml>
</Object>
</Signature>
您可以應用相同的技術。找到Object
節點並將第一個孩子保存到文件中。但是,在這種情況下,XMLSignature
提供getObjects
方法來獲取簽名的對象
//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));
非常感謝。優雅的解決方 – Mirko