使用iText 7解密带密码保护的PDF遇到BadPasswordException如何解决?
iText 7解密加密PDF报错问题解决
问题描述
我参考iText 7知识库站点提供的示例,尝试在不提供所有者密码的情况下解密受密码保护的PDF,但是示例程序抛出了BadPasswordException错误。
该受密码保护的PDF采用256-bit AES密码安全机制,程序使用的依赖为itext7-core v7.1.16。
测试代码:
public class DecryptPdf3 { public static final String SRC = "./src/main/resources/pdfs/THISISATEST_PWP.pdf"; public static final String DEST = "./target/sandbox/security/decrypt_pdf3.pdf"; public static void main(String[] args) throws Exception { File file = new File(DEST); file.getParentFile().mkdirs(); new DecryptPdf3().manipulatePdf(DEST); } protected void manipulatePdf(String dest) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC).setUnethicalReading(true), new PdfWriter(dest)); pdfDoc.close(); } }
报错信息:
Exception in thread "main" com.itextpdf.kernel.crypto.BadPasswordException: Bad user password. Password is not provided or wrong password provided. Correct password should be passed to PdfReader constructor with properties. See ReaderProperties#setPassword() method. at com.itextpdf.kernel.crypto.securityhandler.StandardHandlerUsingAes256.initKeyAndReadDictionary(StandardHandlerUsingAes256.java:253) at com.itextpdf.kernel.crypto.securityhandler.StandardHandlerUsingAes256.<init>(StandardHandlerUsingAes256.java:89) at com.itextpdf.kernel.pdf.PdfEncryption.<init>(PdfEncryption.java:247) at com.itextpdf.kernel.pdf.PdfReader.readDecryptObj(PdfReader.java:1300) at com.itextpdf.kernel.pdf.PdfReader.readPdf(PdfReader.java:734) at com.itextpdf.kernel.pdf.PdfDocument.open(PdfDocument.java:1945) at com.itextpdf.kernel.pdf.PdfDocument.<init>(PdfDocument.java:331) at com.itextpdf.kernel.pdf.PdfDocument.<init>(PdfDocument.java:299)
问题原因
你混淆了setUnethicalReading参数的作用范围:
- 该参数仅用于绕过PDF的所有者权限限制,也就是你已经可以正常打开PDF(知道用户密码),但是因为所有者权限限制无法修改、打印、复制内容的场景,开启该参数可以忽略这些权限限制。
- 你的PDF设置了非空的用户打开密码,256位AES加密机制下,没有正确的用户密码根本无法解密文件的核心内容,
setUnethicalReading没有能力绕过用户密码验证,所以才会抛出密码错误的异常。
解决方法
如果你知道该PDF的用户打开密码,修改代码传入正确的密码即可:
import java.nio.charset.StandardCharsets; import com.itextpdf.kernel.pdf.ReaderProperties; protected void manipulatePdf(String dest) throws Exception { // 替换为实际的PDF用户打开密码 byte[] userPassword = "你的PDF用户密码".getBytes(StandardCharsets.UTF_8); PdfReader reader = new PdfReader(SRC, new ReaderProperties().setPassword(userPassword)); // 开启参数绕过所有者权限限制 reader.setUnethicalReading(true); PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest)); pdfDoc.close(); }
如果你不知道该PDF的用户密码,没有办法通过iText或者其他工具直接解密256位AES加密的PDF,这种加密强度目前没有公开的破解方案。
内容的提问来源于stack exchange,提问作者michadev
相关产品推荐
相关产品推荐

