Password-protecting PDFs in JavaScript: what the encryption hides and what it doesn't
Adding a password to a PDF in JavaScript takes three lines. Knowing what that password actually protects takes a bit longer. I built a browser-only PDF protect tool and ran a few experiments along the way with @cantoo/pdf-lib (a maintained pdf-lib fork that supports encryption) and pdfjs-dist . Here is what I learned. The basic version import { PDFDocument } from ' @cantoo/pdf-lib ' ; const doc =…
When you add a password to a PDF using JavaScript, it actually consists of two passwords: a user password and an owner password. The user password is required to open the file, while the owner password is needed to change permissions like printing, copying, and editing. If the user password is left empty and only an owner password is set, the document can still be opened without a password.
The permissions flags are stored as a number in the PDF file, and the viewer decides whether to respect them. Firefox's PDF viewer (pdf.js) ignores these permissions by default. However, if you want to enforce certain permissions, you need to explicitly set them in the encryption options.
PDF encryption works on strings and streams, such as page content, images, fonts, and metadata values. While the encrypted file may appear to hide the content, anyone with the file can still see the page count, size, and other metadata values. Omitting object streams in the encryption process does not fully hide this information.
The encryption algorithm used is less important than the strength of the password. PDF encryption algorithms like RC4-40 and RC4-128 are broken, so it's recommended to use AES-128 or AES-256. The weak point of PDF encryption is the password itself. If the password is weak or guesses can be made offline with no rate limits, the encryption is not secure.
Therefore, it's essential to use a long, strong password composed of several random words, and to send the password through a separate communication channel than the encrypted file.
Before distributing the encrypted PDF, it's crucial to verify that the file is indeed encrypted correctly. You can do this by attempting to open the file with the correct password, with a wrong password, and without a password using a PDF viewer library like pdfjs-dist. If the file opens successfully without a password or with an incorrect password, then the encryption has not been applied properly.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.