Digital signing a PDF file with security set shows that the document is altered or corrupted

[Repost]
When signing a normal PDF file, the certificate shown at Adobe Reader is valid. But if I change the security setting of this PDF file and sign again, Adobe Reader shows that the document has been altered. I tried another PDF library but has no such issue.

permission.gif (42.5 KB)
document_altered.gif (62.9 KB)

@fw1

In order to investigate the issue further on our end, I request you to please share the source file, used sample code and generated PDF reproducing the issue.

Here is the source code:

import java.awt.Rectangle;
import java.io.FileInputStream;

import com.aspose.pdf.License;
import com.aspose.pdf.PKCS7;
import com.aspose.pdf.facades.PdfFileSignature;

public class AsposeSignTest {

	public static void main(String[] args) {
		String sourceFile = "original_with_security.pdf";
		String signatureImageFile = "test_signature.png";
		String pfx = "test.pkcs12";
		String pfxPassword = "password";
		String outputFile = "aspose_sign.pdf";
		String licenseFile = "Aspose.Total.Java.lic";
		
		try {
			// Load aspose license
			try (FileInputStream is = new FileInputStream(licenseFile)){
				License license = new License();
				license.setLicense(is);
			} catch (Exception e) {
				throw e;
			}
			
			// Create PdfFileSignature object and bind input PDF files
			PdfFileSignature pdfSign = new PdfFileSignature();
			pdfSign.bindPdf(sourceFile);

			// create a rectangle for signature location
			Rectangle rect = new Rectangle(100, 100, 200, 100);

			// Set signature appearance
			pdfSign.setSignatureAppearance(signatureImageFile);

			// Create signature
			PKCS7 signature = new PKCS7(pfx, pfxPassword); // PKCS#7 or
			
			signature.setShowProperties(false);
			pdfSign.sign(1, "", "", "", true, rect, signature);

			// save output PDF file
			pdfSign.save(outputFile);
			System.out.println("Signed file saved at " + outputFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

And the corresponding files:
original_with_security.pdf (145.8 KB)
aspose_sign.pdf (164.5 KB)
test_signature.png (6.7 KB)

@fw1

Can you please also share the “test.pkcs12” as it has been referred in the code and it is missing. We are unable to use the sample code shared because of this.

Here it is.
test.pkcs12.zip (2.7 KB)

@fw1

Thank you for sharing the information. I have been able to reproduce the issue on our end. A ticket with ID PDFJAVA-40407 has been created in our issue tracking system to further investigate the issue on our end. This thread has been linked with the issue so that you may be notified once the issue will be fixed.

The issues you have found earlier (filed as PDFJAVA-40407) have been fixed in Aspose.PDF for Java 22.8.