How can I sign document with apache santuario so that The signature comes inside the tag instead of the end of the MyXML tag?
<MyXML>
<SignaturePlace></SignaturePlace>
<DataToSign>BlaBlaBla</DataToSign>
</MyXML>
Inside the standart JSE dsig library there is javax.xml.crypto.dsig.dom.DOMSignContext class which constructor takes 2 parameters - the RSA private key and the location of the resulting XMLSignature's parent element. Is there something similar inside the apache santuario's implementation?
Yes, you can do this with Apache Santuario.
Here is example code for doing this with for you example XML 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 easy because you wanted the signature to be the last child of the outermost node. If you want to insert the signature before the 3rd child node, you would first obtain a Node that points to the node you want to insert the signature before, and then use the "insertBefore()" method.
final Node thirdChildNode = document.getFirstChild().getNextSibling().getNextSibling();
document.getDocumentElement().insertBefore(signature.getElement(), thirdChildNode);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With