Search code examples
javapdfbox

Why password protected PDF using PDFBOX is opening without password in Microsoft Edge browser?


I have encrypted a pdf file using PDFBOX (v 2.0.16). When I am trying to open this password protected file using adobe acrobat reader its asking for password to unlock it but when I am trying to open it with Microsoft Edge (v 44.18362.449.0) its opening it directly without asking for password.

Below is the sample code used for lock file with password -

private void lockPDFWithPassword(final OutputStream os) throws IOException {
    PDDocument pdDocument = PDDocument.load(((ByteArrayOutputStream) os).toByteArray());
    AccessPermission ap = new AccessPermission();
    StandardProtectionPolicy spp = new StandardProtectionPolicy("sampleOwnerPassword", "sampleUserPassword", ap);
    spp.setEncryptionKeyLength(128);
    spp.setPermissions(ap);
    pdDocument.protect(spp);
    pdDocument.save(os);
    pdDocument.close();
    os.close();
}

Below is the password protected file link -

https://drive.google.com/open?id=1ifcfzGSA_Qr37TzmTqU4Qi14OdVVsdJV


Solution

  • These are two files concatenated. The first one is the unencrypted file, then comes the encrypted file. When separating the two, it works properly.

    The reason for the weird behavior is that PDF viewers have strategies to display broken files. I guess one viewer used the first one, another used the second one.

    The fix the effect, do this:

    os.reset();
    

    before saving so that it writes to the beginning of the ByteArrayOutputStream.