Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Santuario signature element location

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?

like image 600
Georgi Georgiev Avatar asked Nov 13 '22 09:11

Georgi Georgiev


1 Answers

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);
like image 94
Raskolnikov Avatar answered Nov 15 '22 06:11

Raskolnikov