Skip to content
How to lock a PDF document with a password

How to lock a PDF document with a password

Call Encrypt on the writer before writing the document. It takes a user password, an owner password, and the options that decide the algorithm and the permissions:

import (
    "github.com/unidoc/unipdf/v5/core/security"
    pdf "github.com/unidoc/unipdf/v5/model"
)

permissions := security.PermPrinting |
    security.PermFullPrintQuality |
    security.PermAnnotate |
    security.PermFillForms

encryptOptions := &pdf.EncryptOptions{
    Permissions: permissions,
    Algorithm:   pdf.AES_256bit,
}

pdfWriter := pdf.NewPdfWriter()
if err := pdfWriter.Encrypt([]byte(userPassword), []byte(ownerPassword), encryptOptions); err != nil {
    return err
}

Set the algorithm explicitly

EncryptionAlgorithm is an int whose constants start at iota, and RC4_128bit is first. It is therefore the zero value, so an EncryptOptions that sets only Permissions encrypts with RC4.

RC4 is obsolete and should not be used for anything you care about. Set Algorithm on every call. AES_256bit needs PDF 2.0 and AES_128bit needs PDF 1.6, so pick AES_128bit if you need to stay compatible with older readers.

The two passwords do different jobs

The user password is required to open the document. The owner password bypasses the permissions and grants full access.

Leaving the user password empty is the common setup: anyone can open the file, the permissions apply to them, and whoever holds the owner password can do anything. That is why a document can be encrypted and still open without a prompt, which surprises people reading it back in code. See PDF viewer opens but UniPDF says encrypted.

Permissions are honored by convention

The permission bits ask a viewer to withhold printing, editing, extraction and so on. A compliant reader obeys them; a tool that ignores them can still do as it likes, and the owner password removes the restriction entirely.

They deter casual editing rather than enforce anything. Where the content itself must be protected, the encryption is what does the work, so the strength of the password and the algorithm matter more than the permission set.

For the full worked example, see Protect a PDF.

Last updated on