I recently tried to move to iText7, but I have some issues. I already have a PDF and I am trying to lock and restrict permissions on this PDF. I used the same approach with itext5, but the result is not the same. To be more precise:
I used
PdfWriter writer = new PdfWriter(fos, new WriterProperties() .setPublicKeyEncryption(chain, new int[EncryptionConstants.ALLOW_DEGRADED_PRINTING], EncryptionConstants.ENCRYPTION_AES_256));
but nothing happened, then I tried
2.
PdfWriter writer = new PdfWriter(fos, new WriterProperties()
.setStandardEncryption("lala".getBytes(), "lala".getBytes(),
EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ENCRYPTION_AES_256,
EncryptionConstants.ENCRYPTION_AES_256));
nothing happened again. Do you happen to know something about it ?
Full code of the method:
public void signPDF(InputStream inputStream, HttpServletResponse response) {
LOG.debug("Inside signPDF...");
Security.addProvider(new BouncyCastleProvider());
try(OutputStream os = response.getOutputStream();
PdfReader reader = new PdfReader(inputStream);
PdfWriter writer = new PdfWriter(os, new WriterProperties().setStandardEncryption(null, "test".getBytes(), EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA))) {
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(p12Path), keystorePassword.toCharArray());
String alias = ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, keystorePassword.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
BouncyCastleProvider provider = new BouncyCastleProvider();
ITSAClient tsc = new TSAClientBouncyCastle(tsaClient, "", "");
PdfSigner signer = new PdfSigner(reader, writer.getOutputStream(), true);
PdfSignatureAppearance appearance = signer.getSignatureAppearance()
.setReason("Sign")
.setLocation("Test")
.setReuseAppearance(false);
signer.setFieldName("sig");
IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, provider.getName());
IExternalDigest digest = new BouncyCastleDigest();
System.out.println(signer.getDocument().getNumberOfPages());
addWatermark(appearance,signer);
signer.signDetached(digest, pks, chain, null, null, tsc, 0, PdfSigner.CryptoStandard.CMS);
} catch (Exception e) {
LOG.error("Error while writing to outputstream",e);
}
}
Now it is signed, it has watermark, but it is not locked (i.e to copy the content)
PdfWriterwith the encryption information is not used at all. I'll try and correct the code later. - mkl