Apache Santuario签名元素位置

Geo*_*iev 5 java xml apache signature

如何使用apache santuario签署文档,以便签名位于标记内而不是MyXML标记的末尾?

<MyXML>
    <SignaturePlace></SignaturePlace>
    <DataToSign>BlaBlaBla</DataToSign>
</MyXML>
Run Code Online (Sandbox Code Playgroud)

在标准的JSE dsig库中有javax.xml.crypto.dsig.dom.DOMSignContext类,构造函数接受2个参数 - RSA私钥和生成的XMLSignature的父元素的位置.在apache santuario的实现中是否有类似的东西?

Ras*_*kov 1

是的,您可以使用 Apache Santuario 来做到这一点。

下面是使用上面的示例 XML 执行此操作的示例代码:

// Assume "document" is the Document you want to sign, and that you have already have the cert and the key

// Construct the signature and add the necessary transforms, etc.
XMLSignature signature = new XMLSignature(document, null, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
final Transforms transforms = new Transforms(document);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
signature.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

// Now insert the signature as the last child of the outermost node
document.getDocumentElement().appendChild(signature.getElement());

// Finally, actually sign the document.
signature.addKeyInfo(x509Certificate);
signature.addKeyInfo(x509Certificate.getPublicKey());
signature.sign(privateKey);
Run Code Online (Sandbox Code Playgroud)

这种情况很简单,因为您希望签名是最外层节点的最后一个子节点。如果你想在第3个子节点之前插入签名,你需要先获取一个指向你想在前面插入签名的节点的Node,然后使用“insertBefore()”方法。

final Node thirdChildNode = document.getFirstChild().getNextSibling().getNextSibling();
document.getDocumentElement().insertBefore(signature.getElement(), thirdChildNode);
Run Code Online (Sandbox Code Playgroud)