Excuse me, there was missing code that is important for understanding the
question (the external signature is the signedHash byte array).
Updated code below:
------------------------------

Imagine that I have signed already the hash of an existing PDF and created
an external signature.
I can do the following and it creates a valid signed PDF with my signature:


 private byte[] signPDFWithSignedHash(PDDocument doc,..., byte[]
signedHash, Calendar cal) {
    byte[] result = null;

    try {

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName(something");
        signature.setLocation("something");
        signature.setLocation("something");
        signature.setSignDate(cal);
        doc.addSignature(signature);
        doc.setDocumentId(cal.getTimeInMillis());
        ExternalSigningSupport externalSigning =
doc.saveIncrementalForExternalSigning(output);
        // Add the signed hash to the prepared document
        externalSigning.setSignature(signedHash);

         [...]

}

However, if I want to make that signature visible using something like the
following, it does produce a PDF with an invalid signature because the
document has been “altered”:


 private byte[] signPDFWithSignedHash(PDDocument doc,..., byte[]
signedHash, Calendar cal) {
    byte[] result = null;

    try {

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName(something");
        signature.setLocation("something");
        signature.setLocation("something");
        signature.setSignDate(cal);

        PDRectangle rect = createSignatureRectangle(doc, humanRect);
        SignatureInterface signatureInterface = null;
        signatureOptions = new SignatureOptions();
        signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc,
doc.getNumberOfPages() - 1, rect, signature, signerLanguage));
        signatureOptions.setPage(doc.getNumberOfPages() - 1);

        doc.addSignature(signature, signatureInterface, signatureOptions);

        doc.setDocumentId(cal.getTimeInMillis());
        ExternalSigningSupport externalSigning =
doc.saveIncrementalForExternalSigning(output);
        // Add the signed hash to the prepared document
        externalSigning.setSignature(signedHash);

        [...]

}

Reply via email to