Skip to content
How to open an encrypted locked PDF

How to open an encrypted locked PDF

Open the file as usual, ask whether it is encrypted, and authenticate before reading anything:

pdfReader, err := model.NewPdfReader(f)
if err != nil {
    return err
}

isEncrypted, err := pdfReader.IsEncrypted()
if err != nil {
    return err
}

if isEncrypted {
    auth, err := pdfReader.Decrypt([]byte("unlockthedoc"))
    if err != nil {
        return err
    }
    if !auth {
        return errors.New("password rejected")
    }
}

Decrypt returns two values and they mean different things. The error reports a problem performing the decryption; the bool reports whether the password was accepted. A wrong password gives you false with a nil error, so checking only err silently continues against a document you never unlocked.

An encrypted document may need no password

Decrypt also tries an empty password before the one you supply. That is what happens with a document carrying only an owner password: it is genuinely encrypted, IsEncrypted returns true, and Decrypt(nil) still authenticates, because the empty user password grants read access.

This is the usual reason a file opens fine in a viewer while your code reports it as encrypted. PDF viewer opens but UniPDF says encrypted covers that case.

Knowing what you are allowed to do

Authenticating tells you the password worked, not what it entitles you to. For that, CheckAccessRights returns the permission set alongside the bool:

auth, perms, err := pdfReader.CheckAccessRights([]byte(password))

Opening with the user password typically grants reading while withholding modification and extraction, so a program that authenticates and then tries to edit can still be doing something the document forbids.

For writing an unprotected copy, see Unlock a password-protected PDF.

Last updated on