pdfbox: trying to decrypt PDF

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

Following this answer I'm trying to decrypt a pdf-document with pdfbox:

PDDocument pd = PDDocument.load(path); if(pd.isEncrypted()){     try {         pd.decrypt("");         pd.setAllSecurityToBeRemoved(true);     } catch (Exception e) {         throw new Exception("The document is encrypted, and we can't decrypt it.");     } 

This leads to

Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/jce/provider/BouncyCastleProvider at org.apache.pdfbox.pdmodel.PDDocument.openProtection(PDDocument.java:1601) at org.apache.pdfbox.pdmodel.PDDocument.decrypt(PDDocument.java:948) ... Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider ... 

The path is correct, so I don't know what's going on. Furthermore, if I have a look at the PDDocument.decrypt(String pw) method, I find this: This will decrypt a document. This method is provided for compatibility reasons only. User should use the new security layer instead and the openProtection method especially.

What does it mean? Could someone give an example how to decrypt a pdf-document correctly with pdfbox?

回答1:

See the dependency list: https://pdfbox.apache.org/1.8/dependencies.html

You need to use the bouncycastle libraries.

<dependency>   <groupId>org.bouncycastle</groupId>   <artifactId>bcprov-jdk15</artifactId>   <version>1.44</version> </dependency> <dependency>   <groupId>org.bouncycastle</groupId>   <artifactId>bcmail-jdk15</artifactId>   <version>1.44</version> </dependency> 

the decrypt() call is indeed deprecated in the current version (1.8.9). Use

pd.openProtection(new StandardDecryptionMaterial("")); 

instead.

Additional advice: download the source code package. You'll find many examples that will help you further.



回答2:

To use the openProtection method you have to provide an instance of DecryptionMaterial. In your case of password protection it would be StandardDecryptionMaterial (from the API):

PDDocument doc = PDDocument.load(in);   StandardDecryptionMaterial dm = new   StandardDecryptionMaterial("password"); doc.openProtection(dm); 

Furthermore, you have to fullfil the Bouncy Castle dependency of PDFBox for using Encryption/Signing. See https://pdfbox.apache.org/1.8/dependencies.html.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!