Password-protecting a PDF in the browser with Web Crypto (AES-256, PDF 2.0)
Most "protect PDF" websites ask you to upload the document first. For a contract or a bank statement that's exactly the wrong trade: you add a password so fewer people can read the file, and the first thing you do is sen
Most "protect PDF" websites ask you to upload the document first. For a contract or a bank statement that's exactly the wrong trade: you add a password so fewer people can read the file, and the first thing you do is send it to a stranger's server.
I wanted the opposite for Widget Pantry: the file never leaves the tab. The catch is that pdf-lib, the library I use for every other PDF tool, can read PDFs but can't encrypt them. So I implemented the encryption part of the spec myself, on top of the Web Crypto API. It turned out to be about 150 lines.
Which encryption?
PDF has accumulated several security handlers over the years. The old ones (RC4, 40/128-bit) are broken or deprecated. The modern one is the standard security handler, revision 6 from ISO 32000-2 (PDF 2.0):
- one random 256-bit file key encrypts every string and stream with AES-256-CBC;
- the passwords don't encrypt the content directly; they only unwrap the file key;
- key derivation uses a deliberately slow hash ("Algorithm 2.B") to make brute force expensive.
Acrobat, Chrome's viewer, Firefox's pdf.js, macOS Preview and most mobile readers open these files.
Step 1: the file key
const fileKey = crypto.getRandomValues(new Uint8Array(32));
That's the key that actually protects the document. Everything else is about storing it safely inside the file.
Step 2: Algorithm 2.B, the hardened hash
Revision 6 derives keys with a loop of SHA-256/384/512 and AES-128-CBC. Each round:
- builds a block of
password + K + userKeyrepeated 64 times, - encrypts it with AES-128-CBC (key = first 16 bytes of K, IV = next 16),
- picks the next hash function from the first 16 bytes of the ciphertext mod 3,
- hashes the ciphertext with it to get the new K.
It runs at least 64 rounds and stops once the last byte of the ciphertext is ≤ round − 32.
Two Web Crypto details made this interesting:
There's no "AES without padding". Web Crypto's AES-CBC always adds PKCS#7 padding. But padding only ever adds a final block, so for input that's already a multiple of 16 bytes you can encrypt and simply cut the result back to the input length:
async function aesCbcNoPad(key, iv, data) {
const k = await crypto.subtle.importKey("raw", key, { name: "AES-CBC" }, false, ["encrypt"]);
const out = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv }, k, data));
return out.slice(0, data.length);
}
"Mod 3 of a 128-bit number" is just a byte sum. The spec says to treat the first 16 bytes as a big-endian integer and take it mod 3. Since 256 ≡ 1 (mod 3), every byte has the same weight, so the sum of the bytes mod 3 gives the same answer. No BigInt needed.
let sum = 0;
for (let i = 0; i < 16; i++) sum += e[i];
const next = ["SHA-256", "SHA-384", "SHA-512"][sum % 3];
Step 3: the /Encrypt dictionary
For each password, the file stores a verifier and a wrapped copy of the file key:
| Entry | What it is |
|---|---|
/U |
hash of the user password + 8-byte validation salt + 8-byte key salt |
/UE |
the file key, AES-256 encrypted with a key derived from the user password |
/O, /OE
|
the same for the owner password (its hash also covers /U) |
/Perms |
the permission flags, encrypted with the file key, so they can't be edited quietly |
A reader asks for a password, recomputes the hash, compares it to /U (or /O), and if it matches, unwraps the file key from /UE (or /OE).
The permission flags (/P) control printing, copying and editing. If you set restrictions without an owner password, I generate a random 32-byte owner password, so nobody can lift them. That's the point of setting them.
Step 4: encrypt every string and stream
Each string and stream gets a fresh random 16-byte IV, prepended to its AES-256-CBC ciphertext:
async function encryptBytes(fileKey, plain) {
const iv = crypto.getRandomValues(new Uint8Array(16));
return concat(iv, await aesCbc(fileKey, iv, plain)); // this time *with* PKCS#7 padding
}
I walk every indirect object pdf-lib loaded, encrypting strings inside dictionaries and arrays recursively and replacing each stream's contents (fixing its /Length).
The gotchas
-
Object streams. Modern PDFs pack objects into compressed "object streams". Their contents would need a different treatment, so I save with
useObjectStreams: falseand let pdf-lib write every object on its own. -
Form appearances. pdf-lib can regenerate form field appearances on save, but that would happen after my encryption pass and leave them in the clear.
updateFieldAppearances: falsekeeps everything inside the pass. -
Version marker. AES-256 is a PDF 2.0 feature. For readers that only know 1.7, the catalog gets Adobe's extension marker:
/Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 8 >> >>. - Password text. Revision 6 passwords are UTF-8, truncated to 127 bytes. I normalise them with NFKC first (the spec asks for SASLprep, which NFKC covers for everyday passwords), so Unicode passwords work, which RC4-era PDFs never handled well.
Testing it
The same code runs in a browser worker and in Node, because both have crypto.subtle. My tests encrypt a PDF and open the result with Mozilla's pdf.js, an independent implementation: the text and metadata must come back with the right password, a wrong password must be refused, non-ASCII and owner passwords must work, and the print/copy/edit restrictions must reach the reader.
Try it
The tool is free and needs no account: Password Protect PDF. Open DevTools → Network while you use it: the PDF and the password never leave the page.
It's part of Widget Pantry, a set of 57 browser-only tools (PDF, images, calculators, developer utilities). Questions about the spec or the code are very welcome in the comments.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.