I am trying out iText java v8.0.3 trial version to sign pdf document. We first need to generate the document hash, and then send this hash to our signing server which returns a PKCS7 signature. We then apply this signature on the original pdf document.
In iText documentation, it is mentioned about PdfPadesSigner class's prepareDocumentForSignature() and addSignatureToPreparedDocument() methods, which I believe would serve our purpose. But the class does not seem to include those methods, when I build against iText v8.0.3 maven dependency.
I tried using v5.5.13.3 PdfPKCS7 getAuthenticatedAttributeBytes method, but I am getting "document has been altered" signature validation error. Also I have no signing certificate to pass to PdfPKCS7 constructor. So checking out the latest version if it directly supports it.
I also saw this question: Pdf hash signing with iText 8.0.3
Kindly help with sample code/APIs to implement this flow.
Here is my code Step 1: hash generation:
pdfTwoPhaseSigner = new PdfTwoPhaseSigner(new PdfReader(inputStream), new FileOutputStream(tmpFileName));
SignerProperties signerProperties = new SignerProperties();
signerProperties.setPageRect(new Rectangle(36, 748, 144, 780));
signerProperties.setFieldName("swa");
signerProperties.setReason("test reason");
signerProperties.setLocation("test location");
SignatureFieldAppearance signatureFieldAppearance = new SignatureFieldAppearance("swa");
signatureFieldAppearance.setContent("Test Name", "Test description"); signerProperties.setSignatureAppearance(signatureFieldAppearance);`
byte[] digestedDocumentBytes = pdfTwoPhaseSigner.prepareDocumentForSignature(signerProperties, "SHA256", PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached, (8192 * 2 + 2), true); // ETSI_CAdES_DETACHED
return digestedDocumentBytes;
Step 2: remote hash signing: returns: byte[] pkcs7, X509Certificate[] chain
Step 3: apply signature to pdf
CMSContainer cms = new CMSContainer();
SignerInfo signerInfo = new SignerInfo();
signerInfo.setSigningCertificate(chain[0]);
signerInfo.setSignature(pkcs7);
signerInfo.setDigestAlgorithm(new AlgorithmIdentifier(DigestAlgorithms.getAllowedDigest("SHA256")));
cms.addCertificates(chain);
cms.setSignerInfo(signerInfo);
outputStream = new FileOutputStream(outputFile);
try (PdfDocument document = new PdfDocument(new PdfReader(new FileInputStream(tmpFileName)))) {
PdfTwoPhaseSigner.addSignatureToPreparedDocument(document, "swa", outputStream, cms);
}
finally {
outputStream.close();
}
Result: The document has been altered or corrupted since the Signature was applied
This appears to have been an incorrect link, the methods you're looking for are in the PdfTwoPhaseSigner class (or see here for the .NET API).
Have you also seen the recent PAdES Signing API examples on the iText Knowledge Base?