是的,您可以使用 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);
这种情况很简单,因为您希望签名成为最外层节点的最后一个子节点。如果要在第 3 个子节点之前插入签名,首先要获取一个指向要在之前插入签名的节点的 Node,然后使用“insertBefore()”方法。
final Node thirdChildNode = document.getFirstChild().getNextSibling().getNextSibling();
document.getDocumentElement().insertBefore(signature.getElement(), thirdChildNode);