Skip to content
Get Security Info

Get Security Info

Before you can process a PDF you often need to know whether it is encrypted at all, and if it is, whether opening it requires a password you don’t have. IsEncrypted answers the first question and Decrypt answers the second. GetEncryptionMethod then reports which filter and key length the document uses.

Doing it

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

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

// An empty user password is the common case: the file is encrypted to
// restrict permissions, not to keep readers out.
auth, err := pdfReader.Decrypt([]byte(""))
if err != nil {
    return err
}
if !auth {
    fmt.Println("has an opening password")
}

fmt.Println(pdfReader.GetEncryptionMethod())

NewPdfReader is what makes this work on a file you have no password for. It does not try to decrypt, so it returns a usable reader for an encrypted document; the page tree and content streams simply aren’t loaded until a Decrypt call succeeds. NewPdfReaderFromFile and NewPdfReaderWithOpts behave differently - they decrypt with ReaderOpts.Password up front and fail with “unable to decrypt password protected file” when that password is wrong, so they are the wrong entry point for an inspection tool.

Decrypt tries the password you pass and then retries with an empty password if the first attempt fails, so Decrypt([]byte("")) returning false means the document has a non-empty user password. It returning true means either the file had no user password or the one you supplied matched.

What GetEncryptionMethod reports

The string is assembled from the encryption dictionary and depends on the revision. For older RC4 documents (V of 1 or 2) you get the filter name and the key length in bits. For V 4 and up you get the stream and string filter names plus every crypt filter in the document with its name and key length in bytes. The permission bitmask is appended in Go syntax at the end.

Call it only after Decrypt has succeeded or on a reader you know is authenticated. On a reader with no crypter at all - an unencrypted file - it returns an empty string rather than an error.

Limitations

The encryption dictionary alone does not tell you whether the password that opens the document is the user password or the owner password. To distinguish those, and to read the permission bits as flags rather than as an integer, use Check Permissions.

Run the example

The example takes one or more input paths and prints a short report per file. Read printSecurityInfo; the rest is argument handling.

git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/security
go run pdf_security_info.go input.pdf

If this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.

View the full source
Last updated on