CMS/PKCS#7 Signature Generation

Print E-mail  

The objective of this example is to sign a text document using the TrustedX signature service. In order to understand this example, it is recommended that first you understand the previously seen example: X.509 Certificate Validation.

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

Unlike the certificate validation example, in order to produce a signature, a signature request must be created via a SmartSignRequest object. As in the previous example we must define the constants and include an authentication header in the request.

SmartSignRequest ssr = new SmartSignRequest(host);

The signature profile to be produced, in this case CMS/PKCS#7, must be defined.

ssr.setProfile(Constants.Profile.CMSPKCS7);

This example intends to produce the signature for the data in the file called HelloWorld.txt, and so the data is included 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. We will also indicate that the signature format will be CMS, and, given that no other details are specified, it is understood that it will be a detached signature.

ssr.setInputBase64Data(Util.readBinaryFileB64(path_in + filename));
ssr.setKeySubjectName(distinguishedName);
ssr.setSignatureType(Constants.SignatureType.CMS);

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 CMS/PKCS#7 signature validation example, you will see how the validity of the generated signature must be checked. In the case of the CMS/PKCS#7 profile, the getSignatureBase64() method must be used to retrieve the signature.

if (UtilTrustedX.checkSW(ssrs.getResultMajor(), ssrs.getResultMinor(), ssrs.getResultMessage())) {
String destFilename = path_out + filename.substring(0, filename.lastIndexOf("."))
+ "SignedSW.txt.p7s";
Util.writeBinaryFileB64(destFilename, ssrs.getSignatureBase64());
}

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/HelloWorldSignedSW.txt.p7s