How to distinguish between two encrypted / secured

2019-07-09 07:07发布

问题:

I have two secured pdf files. One has a password and the other one is secured but without password. I am using PDF Box. How can I identify which file has password and which one is secured but without password?

回答1:

PDF's have two type of encryption -

  • Owner password - Password set by PDF owner / creator to restrict its usage (e.g. edit, print, copy etc)
  • User password - Password set to open / view the PDF

PDF can have only owner password or both; but not only user password. In either case the PDF is termed to be encrypted and there is no direct API to distinguish between two kind of encryption.

In case of PDFBox you can use below code snippet to determine if it is encrypted or not; and distinguish whether it has only owner password or both.

PDDocument pdfDoc = PDDocument.load(new File("path/to/pdf"));
boolean hasOwnerPwd = false;
boolean hasUserPwd = false;
if(pdfDoc.isEncrypted()){
    hasOwnerPwd = true;
    try{
        StandardDecryptionMaterial sdm = new StandardDecryptionMaterial(null);
        pdfDoc.openProtection(sdm);
        hasUserPwd = true;
    } catch(Exception e){
        // handle exception
    }
}

See PDFBox API docs here and here.

EDIT Thanks to Tilman to point out latest code and alternate way to determine / distinguish between two encryption. Updated the code snippet and post accordingly.



标签: java pdf pdfbox