我正在处理 XML 签名。如您所知,XML 签名分为三种类型:enveloped、enveloping、detached。
我找到了关于如何使用 Java 标准 API 来签署/验证文件的很好的教程,但我想知道如何提取(几乎)“原始”内容数据。特别是:
1) 在验证了一个Enveloped XML 签名文件后,“获取”没有签名的 XML 内容的正确方法是什么?
2) 在验证了一个Enveloping XML 签名文件后,“获取”“对象”节点的正确方法是什么?
对于“获取”,我的意思是写入一个单独的物理文件,清理签名(如果可能,使用标准 API)。
提前谢谢你,
请。
米尔科
最佳答案
封装签名
<yourxml>
...
<Signature>....</Signature>
</yourxml>
签名是 XML 文档的一个节点。验证 XML 签名后,找到节点,将其从 DOM 结构中删除并保存文档。
// 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));
关于java - 如何通过xml签名文件提取 "original"内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40418710/