如何通过xml签名文件提取“原始”内容
问题描述:
我正在处理XML签名。如您所知,有三种类型的XML签名:封装,封装,分离。如何通过xml签名文件提取“原始”内容
我发现了很好的关于如何使用java标准API来签名/验证文件的教程,但我想知道如何提取(几乎)“原始”内容数据。特别是:
1)在验证了封装的 XML签名文件之后,没有签名的情况下“获取”XML内容的正确方法是什么?
2)在验证了封装 XML签名文件后,“获取”“对象”节点的正确方法是什么?对于“get”,我的意思是在一个单独的物理文件上写入,清理签名(如果可能,使用标准API)。
预先感谢您,
亲切。
的Mirko
答
封装签名
<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));
答
在@pedrofb答案的包络的情况下,代码工作,如果对象数据是XML结构。但是我在对象节点的平数据,所以获得使用类似的技术的原始数据内容:
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Object");
if (nl.getLength() == 0) {
throw new Exception("*** Cannot find Object element");
}
final String data = nl.item(0).getTextContent();
try {
File target = new File("/path/output.dat");
FileWriter writer = new FileWriter(target);
BufferedWriter bufferedWriter = new BufferedWriter(writer, 8192);
bufferedWriter.write(data);
//flush & close writers
//...
} catch (Exception e) {
//...
}
非常感谢。优雅的解决方 – Mirko