13

I am trying to use iText's PdfReader to check if a given PDF file is password protected or not, but am getting this exception:

Exception in thread "Main Thread" java.lang.NoClassDefFoundError:org/bouncycastle/asn1/ASN1OctetString

But when testing the same code against a non-password protected file it runs fine. Here is the complete code:

try {
    PdfReader pdf = new PdfReader("C:\\abc.pdf");
} catch (IOException e) {
    e.printStackTrace();
}
Perception
  • 79,279
  • 19
  • 185
  • 195
tusharagrawa
  • 371
  • 2
  • 5
  • 20

8 Answers8

9

In the old version of PDFBox

try
{
    InputStream fis = new ByteArrayInputStream(pdfBytes);                       
    PDDocument doc = PDDocument.load(fis);

    if(doc.isEncrypted())
    {
      //Then the pdf file is encrypeted.
    }
}

In the newer version of PDFBox (e.g. 2.0.4)

    InputStream fis = new ByteArrayInputStream(pdfBytes);
    boolean encrypted = false;
    try {
        PDDocument doc = PDDocument.load(fis);
        if(doc.isEncrypted())
            encrypted=true;
        doc.close();
    }
    catch(InvalidPasswordException e) {
        encrypted = true;
    }
    return encrypted;
VHS
  • 9,534
  • 3
  • 19
  • 43
  • after adding pdf box dependency getting compilation error while running the app. – andro-girl Jan 04 '19 at 09:29
  • is there a possibility that this may not throw `InvalidPasswordException` but still `encrypted = true` – Bahadır Yağan Oct 19 '22 at 13:59
  • Nope, if you are trying to load a password-encrypted pdf without specifying a password, it will throw `InvalidPasswordException` as described in the [docs](https://pdfbox.apache.org/docs/2.0.4/javadocs/org/apache/pdfbox/pdmodel/PDDocument.html#load(java.io.InputStream)). – VHS Oct 19 '22 at 18:03
7

Here's a solution that doesn't require 3rd party libraries, using the PdfRenderer API.

 fun checkIfPdfIsPasswordProtected(uri: Uri, contentResolver: ContentResolver): Boolean {
    val parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r")
        ?: return false
    return try {
        PdfRenderer(parcelFileDescriptor)
        false
    } catch (securityException: SecurityException) {
        true
    }
}

Reference: https://developer.android.com/reference/android/graphics/pdf/PdfRenderer

akodiakson
  • 779
  • 1
  • 5
  • 10
  • *"Here's a solution that doesn't require 3rd party libraries"* - As the question is not Android-specific (and the path `"C:\\abc.pdf"` really hints at another OS), the Android graphics PdfRenderer *is 3rd party*... – mkl Jan 31 '19 at 16:41
6

Use Apache PDFBox - Java PDF Library from here:
Sample Code:

try
{
    document = PDDocument.load( "C:\\abc.pdf");

    if(document.isEncrypted())
    {
      //Then the pdf file is encrypeted.
    }
}
Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
  • document is an Object of Which Class or Interface – tusharagrawa Apr 09 '13 at 09:44
  • @Tushar, the "document" object in the above code snippet is an object of the class org.apache.pdfbox.pdmodel.PDDocument. – VHS Nov 02 '16 at 16:06
  • I am getting compilation when i added this library as a gradle dependency – andro-girl Jan 04 '19 at 09:32
  • the document.isEncrypted() verifiy is a read password has been set (correctly answering the question). Remember anyway that it could be not possible to perform the load (case is: the pdf has been encrypted for real) – sataniccrow Sep 23 '21 at 13:59
6

The way I do it is by attempting to read the PDF file using PdfReader without passing a password of course. If the file is password protected, a BadPasswordException will be thrown. This is using the iText library.

Waleed Almadanat
  • 1,027
  • 10
  • 24
  • I am trying the same method but the exception cannot be catched.It is still Throwing the above exception, – tusharagrawa Apr 09 '13 at 09:36
  • I believe you have to resolve the ClassNotFound exception first, then it'll work. – Waleed Almadanat Apr 09 '13 at 09:38
  • Have tried many Times but whenever i am using PDFReader to read normal file it works fine but as i try to read a password protected file a Class Def not FoundException Occurs – tusharagrawa Apr 09 '13 at 09:46
  • 1
    That is because handling protected files require the BouncyCastle library. So, if you [download BouncyCastle](http://www.bouncycastle.org/latest_releases.html) and include it in your project's classpath your code should work just fine. – Waleed Almadanat Apr 09 '13 at 10:19
4
try {
    PdfReader pdfReader = new PdfReader(String.valueOf(file));
    pdfReader.isEncrypted();
} catch (IOException e) {
    e.printStackTrace();
}

Using iText PDF library you can check. If it went to an exception handle it(ask for password)

mkl
  • 90,588
  • 15
  • 125
  • 265
Shivam
  • 109
  • 2
  • 11
  • 1
    Please add an explanation as to why the above would work. – Markoorn Nov 28 '18 at 06:27
  • @Markoorn - PdfReader allows you to check the file is password protected or not using the **isEncrypted() **. If the pdf file is encrypted(password protected) it will give you an exception, in catch block you need to handle it or ask user to enter the password to open the file. Hope it helps you. – Shivam Dec 18 '18 at 05:35
  • 1
    even for non-password protected files its returning true. – andro-girl Jan 04 '19 at 09:31
  • 1
    @andro-girl which library you are using? make sure that iText (implementation 'com.itextpdf:itextg:5.5.10'). It's working for me. – Shivam Jan 07 '19 at 07:33
2

Try this code:

    boolean isProtected = true;
    PDDocument pdfDocument = null;
    try
    {
        pdfDocument = PDDocument.load(new File("your file path"));
        isProtected = false;

    }
    catch(Exception e){
        LOG.error("Error while loading file : ",e);
    }
    Syste.out.println(isProtected);

If your document is password protected then it can not load document and throw IOException. Verified above code using pdfbox-2.0.4.jar

Nitin
  • 2,701
  • 2
  • 30
  • 60
  • To be more exact: it will throw InvalidPasswordException, which is an IOException. Note that some documents are password protected, but with an empty user password. – Tilman Hausherr Jan 24 '17 at 09:22
1
public boolean checkPdfEncrypted(InputStream fis) throws IOException {
    boolean encrypted = false;
    try {
        PDDocument doc = PDDocument.load(fis);
        if (doc.isEncrypted())
            encrypted = true;
        doc.close();
    } catch (
            IOException e) {
        encrypted = true;
    }
    return encrypted;
}

Note: There is one corner case in iText some file are encrypted protected but open without a password, to read those files and add water mark like this

PdfReader reader = new PdfReader(src);
reader.setUnethicalReading(true);
Boken
  • 4,825
  • 10
  • 32
  • 42
Aasim ali
  • 318
  • 4
  • 6
0

I didn't want to use any third party library, so i used this -

            try {
                new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
            } catch (Exception e) {
                e.printStackTrace();
                // file is password protected
            }

If the file was password protected, i didn't use it.

User9211
  • 194
  • 1
  • 2
  • 17