Search code examples
itext7

Why 'Not enough space' exception thrown when applying TSA?


I am trying to apply TSA using code below, Why I got: "Not enough space" exception

Prepare signature container:

        ITSAClient tsaClient = new TSAClientBouncyCastle("https://freetsa.org/tsr", "", "");

        PdfSigner signer = new PdfSigner(new PdfReader("results/example.pdf"), new FileStream("results/prepared1.pdf", FileMode.Create), new StampingProperties().UseAppendMode());
        signer.SetFieldName("Signature1");
        signer.SetCertificationLevel(0);
        signer.Timestamp(tsaClient, "Signature1");   // EXCEPTION THROWN HERE

        PdfSignatureAppearance sigAppearance = signer.GetSignatureAppearance();
        sigAppearance
            .SetPageRect(new Rectangle(144, 144, 200, 100))
            .SetPageNumber(1)
            .SetContact("This is contact1")
            .SetReason("This is reason1")
            .SetLocation("This is location1")
            .SetSignatureCreator("This is signature creator");

        ExternalEmptySignatureContainer container = new ExternalEmptySignatureContainer();
        signer.SignExternalContainer(container, 8192);

        byte[] dataToSign = container.Data;

        return dataToSign;enter code here

Not enough space


Solution

  • You use the TSAClientBouncyCastle constructor without a size estimate:

    ITSAClient tsaClient = new TSAClientBouncyCastle("https://freetsa.org/tsr", "", "");
    

    So a default of 4 KB is assumed. Thus, when you apply a document time stamp

    signer.Timestamp(tsaClient, "Signature1");
    

    a place holder for a 4 KB time stamp token is reserved, then a time stamp is requested. The error message you receive here now tells you that the actually retrieved time stamp apparently is larger.

    You should, therefore, use a TSAClientBouncyCastle constructor which also accepts a size parameter and set it to e.g. 8 KB = 8192.


    That being said, you seem to misunderstand the Timestamp method: It immediately applies a document time stamp and then closes the document:

        /// <summary>Signs a document with a PAdES-LTV Timestamp.</summary>
        /// <remarks>
        /// Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.
        /// <br /><br />
        /// NOTE: This method closes the underlying pdf document. This means, that current instance
        /// of PdfSigner cannot be used after this method call.
        /// </remarks>
        /// <param name="tsa">the timestamp generator</param>
        /// <param name="signatureName">
        /// the signature name or null to have a name generated
        /// automatically
        /// </param>
        public virtual void Timestamp(ITSAClient tsa, String signatureName)
    

    Thus, you'll run into other errors after fixing the timestamp token size estimate problem!