Yes, you can do it with Apache Santuario.
Here is the sample code for this for the XML example above:
// 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);
This case is simple because you wanted the signature to be the last child from the external node. If you want to insert a signature before the third child element of a node, you will first get a Node that points to the Node that you want to insert the labels earlier, and then use the insertBefore () method.
final Node thirdChildNode = document.getFirstChild().getNextSibling().getNextSibling(); document.getDocumentElement().insertBefore(signature.getElement(), thirdChildNode);
source share