8

is it possible to check if pdf is password protected using ghostscript? what would be the command? I know you can strip pdf password using ghostscript, but all I want to do is just checking if PDF is password protected or security enabled.

Aman
  • 1,624
  • 3
  • 15
  • 25
  • Having started a bounty, I would also like to know whether it is possible to detect password-protected PDFs with other tools. – Benoit Dec 09 '10 at 08:20

5 Answers5

10

checkuserpasswdPDF.sh:

#!/bin/sh

GS=~/gs/bin/gs
output=`$GS -dBATCH -sNODISPLAY "$1" 2>&1`
gsexit=$?

if [ "$gsexit" == "0" ]; then
  echo "Not user-password protected"
  exit 0;
else
  found=`echo "$output" |grep -o "This file requires a password"`
  if [ -z "$found" ]; then
    echo "Failed to invoke gs" 
    exit $gsexit
  else
    echo "Protected"
    exit 0;
  fi  
fi

Checks for user-password protected PDFs: checkuserpasswdPDF.sh test.pdf.

GS disregards owner-passwords (see this).

khachik
  • 28,112
  • 9
  • 59
  • 94
3

You can test using pdfinfo

pdfinfo $filename &>/dev/null;
if [[ $? -eq 1 ]] ; then
   echo "File can not be opened for reading"
fi
Reza S
  • 9,480
  • 3
  • 54
  • 84
2

Using a bat file, you can do a little workaround by searching for "Encrypt" in the pdfs. Its quiet fast to search through many files.

Findstr /M /I "Encrypt" *.pdf 

This will return all filenames that are secured (since "Encrypt" will be written in the file as dos reads it)

Maybe this is something someone can use. I use:
for /f %%a in ('Findstr /M /I "Encrypt" *.pdf') do move %%a c:\tempfiles\
to move all secured pdf's to c:\tempfiles. From there I use ghostscript to remove the security, and move it back to original folder.

TrueTom
  • 31
  • 10
  • 1
    Keep in mind that this doesn't distinguish between owner password protection and user password protection. This test shows if it has _any_ password protection – Reza S Jul 25 '18 at 21:10
2

With pdftk it is possible to detect a user password or owner password by just trying to do a dump_data operation.

 protected=0
 pdftk "input.pdf" dump_data output /dev/null dont_ask || protected=1

The problem here is that you don't know what the password prevents: reading, extracting data, modifying...?

Benoit
  • 76,634
  • 23
  • 210
  • 236
  • 2
    i tried something similar, but it was limiting and pdftk wasn't always giving me correct result. – Aman Dec 10 '10 at 11:23
0

The answer of @Benoit gives ugly errors on console, but works.

So I would put this to an oneliner with suppression of error output:

protected=0 && pdftk "input.pdf" dump_data output /dev/null dont_ask 2>/dev/null || protected=1