3

When using iText to sign PDF document with external signature, I have to prepare empty signature container first:

PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setVisibleSignature(rectangle, 1, fieldName);
appearance.setCertificate(chain[0]);
ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.signExternalContainer(appearance, external, 8192);

The last parameter of MakeSignature.signExternalContainer(appearance, external, 8192); is estimatedSize - the reserved size for the signature.

In case that the PDF has for example 10 000 bytes and estimatedSize is set to 10 000 bytes and actual signature container has 1 000 bytes, then the resulting PDF will be of size of original PDF + estimatedSize, instead of size of original PDF + size of signature container, which could be much larger.

Is there any way how to calculate the estimatedSize parameter exactly to avoid such increase in size of signed PDF?

Or what are prerequisites to be able to calculate the exact size for the signature?

Are there other way how to sign PDF document using iText to avoid this?

user1563721
  • 1,373
  • 3
  • 28
  • 46

1 Answers1

1

There's already an answer to this question here: https://stackoverflow.com/a/29345340/1622493 where somebody indicates that choosing 0 for the value of the estimated size will cause iText to make the estimation in your place.

The is no way you can calculate the exact size for the signature, but in section 3.5 of my book Digital signatures for PDF documents, I explain in detail which factors you should take into account:

enter image description here

Suppose that you have a signature created with a certificate that is part of a chain for which 2 OSCP response need to be added, you need to add 2 times 4,192 bytes. If you want to add a CRL, then you'll need to estimate how many bytes will be taken by the CRL. In case of a good CA, this could be a low number. In case of a bad CA, the CRL could be huge. (In other words: the trade-off that is made between choosing for CRL or OSCP will depend on the CA.)

Another very useful indication would be the number of bytes that you are sending to the client to be signed on the client-side. If you're already sending a hash that consists of more than 10,000 bytes, then you shouldn't expect that the signed hash will be less than 10,000 bytes. How much bigger the signed hash will be depends on the signing algorithm and the length of the key.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165