Open in a new tab

Encrypt a PDF with AES-256 (the ISO 32000-2 standard security handler), see the plain reader refuse it with a typed error, open it with the right password, refuse the wrong one.

Uses @awacloud/pdf (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.

When to use it

Handing out a document that only its recipient may open — a pay slip, a contract draft — produced on the user's machine. The user password opens the file in any PDF viewer; the owner password guards the permission flags (printing, copying, …) viewers are asked to honour.

Copy-paste steps

  1. npm install @awacloud/pdf (it depends on @awacloud/fw and @awacloud/fonts).
  2. Serve node_modules/@awacloud/fw/src/, node_modules/@awacloud/pdf/src/ and node_modules/@awacloud/fonts/src/ at /vendor/fw/, /vendor/pdf/ and /vendor/fonts/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy.
  4. Feed encrypt() your own bytes (any PDF pdf.read() accepts) and your own passwords; pick the permission mask from the Table 22 bits in READ_AND_PRINT.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/pdf's fw_require, pkg_require and modules; the modules used are pdfEncryptedWriter, pdfWriter (assembleIndirects), pdfBuilder and pdf, plus fw's uuid for a throwaway owner password.
  • Encrypt: pdf.read(bytes) then pdfWriter.assembleIndirects(doc) turns an existing file into its object graph, and pdfEncryptedWriter.writeEncryptedDocument({ indirects, root, info, id, encrypt: { version: 5, revision: 6, keyBits: 256, userPassword, ownerPassword, permissions } }) writes it back with every string and stream encrypted (AES-256-CBC, /Filter /Standard /V 5 /R 6) under a fresh random file key. The test checks the page text and the Info title are no longer visible in the bytes.
  • Read: pdf.read(bytes) refuses a protected file with the typed pdf/document/encrypted; pdf.read(bytes, { password }) tries the password as the user, then the owner password, and decrypts as it reads; a wrong one throws pdf/document/bad-password. No security-handler internals are needed.
  • Cost: the revision-6 key hardening runs SHA-2 and AES rounds in pure JavaScript; encrypting or opening takes a few seconds here. In a page, run it in a worker so the interface stays responsive (fastCipher: true speeds up a trusted single-user read, see the package's reading options).
  • Not shown: showing the decrypted page text (the read document has no public way yet to resolve a page's content stream), the permission flags read back, the AES-256-GCM crypt filter, AES-128 and RC4 (legacy, V=4), public-key encryption.

Code

main.js

javascriptAGPL-3.0-only76 lines

// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { uuid } from '@awacloud/fw/crypto/utils/uuid.js';
import { fw_require, pkg_require, modules } from '@awacloud/pdf';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...pkg_require, ...modules]);
rt.registerAllDeep([uuid]);
const PDF = rt.resolve('pdf');
const BUILDER = rt.resolve('pdfBuilder');
const WRITER = rt.resolve('pdfWriter');
const ENCRYPTED = rt.resolve('pdfEncryptedWriter');
/** ISO 32000-2 Table 22: every permission except modify, copy, annotate, fill forms and assemble. */
export const READ_AND_PRINT = -4 & ~(0x008 | 0x010 | 0x020 | 0x100 | 0x400);
const latin1 = (/** @type {Uint8Array} */ bytes) => new TextDecoder('latin1').decode(bytes);

/** One page with one line of text: the document to protect. @param {string} [line] */
export function buildSample(line = 'Confidential: the launch date is 2026-11-02') {
    return BUILDER.builder().addPage().addFont({ name: 'F1', baseFont: 'Helvetica' })
        .addContent(`BT /F1 16 Tf 72 720 Td (${line}) Tj ET`).addMetadata({ Title: 'Protected sample' }).build();
}

/**
 * Password-protect an existing PDF with the ISO 32000-2 standard security
 * handler, AES-256 (V=5, R=6): every string and stream of the object graph is
 * encrypted with a fresh file key, the Info dictionary included.
 * @param {Uint8Array} bytes
 * @param {{ userPassword: string, ownerPassword: string, permissions?: number }} access
 */
export function encrypt(bytes, { userPassword, ownerPassword, permissions = READ_AND_PRINT }) {
    const doc = PDF.read(bytes);
    return ENCRYPTED.writeEncryptedDocument({
        indirects: WRITER.assembleIndirects(doc), root: doc.trailer.root, info: doc.trailer.info, id: doc.trailer.id,
        encrypt: { version: 5, revision: 6, keyBits: 256, userPassword, ownerPassword, permissions },
    }).bytes;
}

/**
 * Read a PDF: `pdf.read(bytes, { password })` tries the password as the user,
 * then the owner password, and decrypts as it reads. Without a password a
 * protected file is refused with the typed `pdf/document/encrypted`.
 * @param {Uint8Array} bytes @param {string} [password]
 * @returns {{ ok: true, pages: number, mediaBox: number[] } | { ok: false, code: string }}
 */
export function open(bytes, password) {
    try {
        const doc = PDF.read(bytes, { password });
        return { ok: true, pages: doc.pages.length, mediaBox: doc.pages[0].mediaBox };
    } catch (err) {
        return { ok: false, code: /** @type {any} */ (err).code };
    }
}

/** @param {string} id @param {string} text */
const show = (id, text) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = text; };
const password = /** @type {HTMLInputElement} */ (document.getElementById('password'));
let protectedBytes = /** @type {Uint8Array | null} */ (null);

document.getElementById('encrypt')?.addEventListener('click', () => {
    const original = buildSample();
    // The owner password unlocks every permission: a random one nobody keeps.
    protectedBytes = encrypt(original, { userPassword: 'reader', ownerPassword: String(rt.resolve('uuid').v4()) });
    const visible = latin1(protectedBytes).includes('Confidential') ? 'yes' : 'no';
    show('encrypted', `${original.length} → ${protectedBytes.length} bytes; plaintext in the file: ${visible}`);
    const plain = open(protectedBytes);
    show('refused', `pdf.read() without a password: ${plain.ok ? 'read' : plain.code}`);
    show('opened', '—');
    /** @type {HTMLButtonElement} */ (document.getElementById('open')).disabled = false;
});
document.getElementById('open')?.addEventListener('click', () => {
    if (!protectedBytes) return;
    const result = open(protectedBytes, password.value);
    if (!result.ok) return show('opened', `refused: ${result.code}`);
    const [, , width, height] = result.mediaBox;
    show('opened', `password accepted: ${result.pages} page, ${width} × ${height} pt`);
});

index.html

htmlAGPL-3.0-only46 lines

<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>pdf · Password-protect a PDF with AES-256</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
    "@awacloud/pdf": "/vendor/pdf/main.js", "@awacloud/pdf/": "/vendor/pdf/",
    "@awacloud/fonts": "/vendor/fonts/main.js", "@awacloud/fonts/": "/vendor/fonts/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Password-protect a PDF with AES-256</h1>
    <p><button id="encrypt" type="button">Encrypt the sample (user password: <code>reader</code>)</button></p>
    <dl>
      <dt>Encrypted</dt><dd id="encrypted">—</dd>
      <dt>Plain reader</dt><dd id="refused">—</dd>
      <dt>Opened</dt><dd id="opened" aria-live="polite">—</dd>
    </dl>
    <p>
      <label for="password">Password</label>
      <input id="password" type="password" value="reader" autocomplete="off">
      <button id="open" type="button" disabled>Open</button>
    </p>
  </main>
  <!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
  <footer id="legal" aria-label="Legal notices">
    <p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
      version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
      <a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
    <p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
    <ul>
      <li>@awacloud/fw · Apache-2.0</li>
      <li>@awacloud/pdf · AGPL-3.0-only</li>
      <li>@awacloud/fonts · AGPL-3.0-only</li>
    </ul>
  </footer>
  <!-- aln:end -->
</body>
</html>