iText Java Signing PDF DocumentException: Not enou

2019-01-20 16:12发布

问题:

I am using iText 5.5.5 for Java and I would like to create signed PDF with external signature as follows:

Take the PDF document that should be signed and create PDF with empty signature and provide BASE64 encoded bytes to be signed by external signature mechanism:

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

InputStream is = appearance.getRangeStream();
byte[] toSign = getBytes(is);
this.b64String = new String(Base64.encode(toSign));

Sign b64String with external signature mechanism providing signature as PKCS#7 signed data in BASE64.

Create ExternalSignatureContainer to have just the PKCS#7 signed data from external signing mechanism:

public class MyExternalSignatureContainer implements ExternalSignatureContainer {
    protected byte[] sig;

    public MyExternalSignatureContainer(byte[] sig) {
        this.sig = sig;
    }

    @Override
    public void modifySigningDictionary(PdfDictionary arg0) {
    }

    @Override
    public byte[] sign(InputStream arg0) throws GeneralSecurityException {
        return sig;
    }
}

Create signed PDF document with MyExternalSignatureContainer:

PdfReader reader = new PdfReader(dest);
FileOutputStream os = new FileOutputStream(signedpdf);
ExternalSignatureContainer external = new MyExternalSignatureContainer(signedData);
MakeSignature.signDeferred(reader, "test", os, external);

But I get on the last line MakeSignature.signDeferred(reader, "test", os, external); the following exception:

com.itextpdf.text.DocumentException: Not enough space

Where is the problem and how to resolve it?

回答1:

You have made an estimation that the signature will fit into 8192 bytes. However, the number of bytes of signature byte[] exceeds 8192, hence the exception Not enough space. For instance: your external signature container returns a signature that measures 10000 bytes. iText tells you that 10000 is bigger than 8192 and that you are asking something that is impossible.

How to fix this: make a better estimate when you create the PDF with the empty signature.



回答2:

Say to your container the size is estimated:

MakeSignature.signExternalContainer(appearance, external, 0);

According to MakeSignature API

estimatedSize - the reserved size for the signature. It will be estimated if 0