Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to detect that a PDF is encrypted with PHP

I'm trying to find the best way to detect that a given PDF is encrypted with PHP. I don't need to decrypt it or edit it or anything like that. The idea is to simply provide an error message to a user if they upload an encrypted PDF.

Most of the PDF parsing libraries for PHP that are out there seem to require the entire PDF be read into memory in order to do the parse. For my purpose, reading the entire PDF into memory is unacceptable as the PDF's I am dealing with may be tens if not hundreds of megabytes large.

Shelling out to pdfinfo is not a great option (as I don't like firing up a new process to do this) but that is the solution if there is no other options. I don't know enough about the binary structure of a PDF to even write enough of a parser to detect this so pdfinfo may be the only choice.

TL;DR is there an easy way that is pure PHP (no C extensions) to detect if a PDF is encrypted (aka password protected) that does not read the entire thing into memory?

like image 550
pleonasm Avatar asked Oct 01 '22 04:10

pleonasm


1 Answers

Unfortunately the Encrypt flag (i.e. "/Encrypt") of a PDF is near the end of the file.

Normal file parsing functions read the file from the start of the file to the end (or up to a certain length), hence it logically means that if you want to determine whether the pdf is encrypted/protected or not you may need to read the whole file, and that's why most of the PDF parsing libraries are reading the whole file to do the parsing.

The performance of current servers should handle reading of big PDF file without problem.

Personally I use the following script and it works without any performance problem:

<?php
$filename= "./useruploads/". $uploadedfilename; 
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

if (stristr($contents, "/Encrypt")) 
{echo " (Suspected Enrypted PDF File !)";}
else
{echo " OK ";}  
?>
like image 171
Ken Lee Avatar answered Oct 13 '22 10:10

Ken Lee