javaitextamazon-cloudhsm

signature byte range is invalid after enabling LTV


I am using aws cloudHSM and itext7 to sign the pdf. Everything is fine till i am not enabling LTV.

But after enabling LTV getting error "Atleast one signature has problem" and showing reason signature byte range is invalid.

Below is the code

private void ltvEnable(PdfSigner signer, OutputStream baos, String name11,
        OcspClientBouncyCastle ocspClient, CrlClientOnline crlClient, CustomTSAClient tsc) {
    ByteArrayInputStream signedPdfInput = new ByteArrayInputStream(((ByteArrayOutputStream)baos).toByteArray());
    try {
        
        PdfReader pdfReader = new PdfReader(signedPdfInput);
        PdfDocument document = new PdfDocument(pdfReader.setUnethicalReading(true), new PdfWriter(baos),
                new StampingProperties().useAppendMode());
        LtvVerification ltvVerification = new LtvVerification(document);
        SignatureUtil signatureUtil = new SignatureUtil(document);
        List<String> names = signatureUtil.getSignatureNames();
        String sigName = names.get(names.size() - 1);
        PdfPKCS7 pkcs7 = signatureUtil.readSignatureData(sigName);
        if (pkcs7.isTsp()) { 
            ltvVerification.addVerification(sigName, ocspClient, crlClient, LtvVerification.CertificateOption.WHOLE_CHAIN,
                    LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES);
        } else {
            for (String name : names) {
                ltvVerification.addVerification(name, ocspClient, crlClient, LtvVerification.CertificateOption.WHOLE_CHAIN,
                        LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES);
            }
        }
        
        ltvVerification.merge();
        //signer.timestamp(tsc, null);
        document.close();
        pdfReader.close();

    } catch (IOException | GeneralSecurityException e) {
        logger.error("Error while making signature ltv enabled");
    }
}

Before enabling ltv -:

enter image description here

After -:

enter image description here


Solution

  • In your architecture you have a ByteArrayOutputStream parameter in which you retrieve the pdf to LTV-enable and in which you also in the end return the LTV-enabled result pdf.

    In such an architecture have to clear the ByteArrayOutputStream between retrieving the original content from it and adding the new content to it.

    In your case, therefore, you have to clear it between

    ByteArrayInputStream signedPdfInput = new ByteArrayInputStream(((ByteArrayOutputStream)baos).toByteArray());
    

    and

    PdfDocument document = new PdfDocument(pdfReader.setUnethicalReading(true), new PdfWriter(baos),
                    new StampingProperties().useAppendMode());