The straight forward way to implement signing a PDF with iText 5.5.x using an external signing service or device is to use an IExternalSignature
or IExternalSignatureContainer
implementation in which the respective Sign
method calls the external signing service or code to sign with that device for the data from its argument and returns the result signature.
For the sake of simplicity let's assume your signing service / device can be used to return a full-fledged CMS signature container. In that case one would use an IExternalSignatureContainer
implementation like this:
PdfReader reader = new PdfReader(SRC);
FileStream os = new FileStream(DEST, FileMode.Create);
PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Reason = "For a reason surely";
appearance.Location = "Positively somewhere";
appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
IExternalSignatureContainer externalSignatureContainer = new ExternalServiceContainerSigner();
// Creating the signature
MakeSignature.SignExternalContainer(appearance, externalSignatureContainer, 8192);
with
class ExternalServiceContainerSigner : IExternalSignatureContainer
{
public void ModifySigningDictionary(PdfDictionary signDic)
{
signDic.Put(PdfName.FILTER, PdfName.ADOBE_PPKLITE);
signDic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_DETACHED);
}
public byte[] Sign(Stream data)
{
String hashAlgorithm = "SHA256";
byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm);
// call your external signature service to create a CMS signature
// container for the given document hash and return the bytes of
// that signature container.
return CALL_YOUR_EXTERNAL_SIGNATURE_SERVICE_TO_CREATE_A_CMS_SIGNATURE_CONTAINER_FOR(hash);
}
}
If your signing service / device does not offer to create a CMS signature container but instead only naked signature bytes or a PKCS#1 style signature, you can either
- replace the
CALL_YOUR_EXTERNAL_SIGNATURE_SERVICE_TO_CREATE_A_CMS_SIGNATURE_CONTAINER_FOR
call above by your own code preparing and signing a signature container for the given document hash using the external service / device or
- use an
IExternalSignature
implementation calling your service and MakeSignature.SignDetached
to use that implementation.