In the past, I have tried to decrypt PDFs using PDFBox using the following code:
if (doc.isEncrypted()){
doc.openProtection(new StandardDecryptionMaterial(password));
doc.setAllSecurityToBeRemoved(true);
}
(Note that I don't use doc.decrypt(password)
because the Javadoc for decrypt() says that openProtection() should be used instead, although why it's not just deprecated is beyond me).
Anyway, this has worked fine for quite a while. However, lately I seem to be getting the following exception:
java.io.IOException: javax.crypto.BadPaddingException: Given final block not properly padded
at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:118)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:236)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:212)
at org.apache.pdfbox.pdmodel.encryption.SecurityHandler.encryptData(SecurityHandler.java:316)
at org.apache.pdfbox.pdmodel.encryption.SecurityHandler.decryptStream(SecurityHandler.java:421)
at org.apache.pdfbox.pdmodel.encryption.SecurityHandler.decrypt(SecurityHandler.java:390)
at org.apache.pdfbox.pdmodel.encryption.SecurityHandler.decryptObject(SecurityHandler.java:365)
at org.apache.pdfbox.pdmodel.encryption.SecurityHandler.proceedDecryption(SecurityHandler.java:196)
at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.decryptDocument(StandardSecurityHandler.java:158)
at org.apache.pdfbox.pdmodel.PDDocument.openProtection(PDDocument.java:1598)
<Stack trace continues with my call to openProtection()>
How can I fix this problem?
This is a known issue, which appears to have been introduced as a result of a Java update. At the time of this writing, a fix for this is in review to be included in version 1.8.8, so just upgrade to version 1.8.8 or later and this problem will go away.