XML Signature Generation

Print E-mail  

The objective of this example is to sign an XML document using the TrustedX signature service. In order to understand this example, it is recommended that first you understand the previously seen example: CMS/PKCS#7 Signature Generation.

To try this example, you must download the file called sampleSW3.zip and follow the instructions in Configuration of the Environment.

As in the case of the CMS/PKCS#7 Signature example, we must use a SmartSignRequest object to perform a signature request; however, in this case the signature profile is XADES (or XML).

SmartSignRequest ssr = new SmartSignRequest(host);
ssr.setProfile(Constants.Profile.XADES);

This example intends to produce the signature for the data in the file called Demo.xml, and so the data is included in the request encoded in Base64. Moreover, we will indicate which certificate will be used to generate the signature, by selecting it from the user’s distinguished name.

ssr.setInputXmlBase64(Util.readBinaryFileB64(path_in + filename));
ssr.setKeySubjectName(distinguishedName);         

Given that the type of signature desired is not stated, by default it will be a detached signature. Later, in other signature requests, we will show the other two types of requests possible with an XML signature, i.e. the signature request type for adding the resulting signature inside the original document, known as an enveloped signature, and the signature request type for adding the document inside the generated signature, known as an enveloping signature.

We can also indicate the format in which the resulting signature should be returned - in this case Base64.

ssr.setXmlReturnBase64(true);

Once all the data have been entered in the request, the send() operation is invoked; this operation sends the request to the host and collects the response in a SmartSignResponse object.

SmartSignResponse ssrs = ssr.send();

Once the request has been sent, we can check if it has been processed correctly by consulting the response parameters. The functions of the UtilTrustedX auxiliary class are used for this. If all goes well, the signature is retrieved from the response and is stored in a file. In the XML signature validation example, you will see how the validity of the generated signature must be checked. Given that it was indicated that the response should return a Base64 encoded signature and that it is a XADES profile request, we must use the getSignatureXmlBase64() method to retrieve the signature.

if (UtilTrustedX.checkSW(ssrs.getResultMajor(), ssrs.getResultMinor(), ssrs.getResultMessage())) {
String destFilename = path_out + filename.substring(0, filename.lastIndexOf("."))
+ "SignedDetachedSW.xml";
Util.writeBinaryFileB64(destFilename, ssrs.getSignatureXmlBase64());
}  

After executing the example, we obtain a response, such as the one below, and a file with the signature.

File saved successfully on: data/output/DemoSignedDetachedSW.xml