Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdfbox: trying to decrypt PDF

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?

like image 508
Munchkin Avatar asked Apr 16 '15 13:04

Munchkin


Video Answer


2 Answers

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.

like image 135
Tilman Hausherr Avatar answered Oct 14 '22 00:10

Tilman Hausherr


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.

like image 7
flo Avatar answered Oct 13 '22 22:10

flo