# Encryption and passwords

> Open password-protected PDFs with the built-in prompt or your own, and add, change or remove password protection with RC4 and AES encryption and permission flags.

Birch UI PDF reads and writes the standard password security handler of PDF: RC4 with 40 or 128-bit keys, AES-128 and AES-256. An opened file can be annotated, filled and saved like any other, and stays encrypted with the same key. Certificate (public-key) encryption is not supported.

## Opening a protected file in the viewer

Pass `password` when you know it. Otherwise, and when it is wrong, the viewer asks:

- With `onPasswordRequest`, your function is called with `{ isRetry, fileName }` and returns the password, or `null` or `undefined` to give up. It is called again with `isRetry: true` after a wrong password.
- Without it, a modal prompt is shown, with a message about the wrong password on a retry.

```ts
import { createPdfViewer } from '@birchui/pdf';
declare function showMessage(text: string): void;

const viewer = createPdfViewer(document.querySelector<HTMLElement>('#payslip')!, {
  document: payslipBytes,
  fileName: 'payslip-2026-03.pdf',
  onPasswordRequest: async ({ isRetry, fileName }) => {
    if (isRetry) return null;
    const response = await fetch(`/api/documents/password?file=${encodeURIComponent(fileName)}`);
    return response.ok ? response.text() : null;
  },
});

viewer.ready.catch(() => showMessage('This payslip could not be opened.'));
```

Giving up rejects `viewer.ready` and emits `documentError`. `viewer.load(bytes, { password })` takes a password for the next file. A file that only has an owner password, and so opens without one in other readers, opens without a prompt here too.

## Opening a protected file headlessly

`loadPdfDocument` is the asynchronous form of `openPdfDocument` and decrypts the file:

```ts
import { PdfPasswordError } from '@birchui/pdf';
import { loadPdfDocument } from '@birchui/pdf/engine';

try {
  const pdf = await loadPdfDocument(statementBytes, { password: 'correct horse battery' });
  console.info(pdf.encryption?.algorithm, pdf.encryption?.isOwner, pdf.permissions.print);
} catch (error) {
  if (error instanceof PdfPasswordError) console.warn(error.reason);
  else throw error;
}
```

`PdfPasswordError.reason` is `password-required`, `password-incorrect` or `unsupported` (an encryption scheme other than the standard handler, such as certificate encryption).

`openPdfDocument` is synchronous and cannot decrypt. It returns a document with `isLocked: true`, without annotations and fields; saving it or changing its encryption throws `PdfPasswordError`.

| Property | Meaning |
| --- | --- |
| `isEncrypted` | The file as opened is encrypted |
| `isLocked` | It has not been decrypted |
| `encryption` | `{ algorithm, revision, isOwner, encryptsMetadata }`, or `undefined` for a plain file |
| `permissions` | The eight permission flags. All `true` for a plain file and when the owner password was used. |

## Adding, changing and removing protection

```ts
import { decryptPdf, encryptPdf } from '@birchui/pdf/engine';

const protectedCopy = await encryptPdf(payslipBytes, {
  userPassword: 'mei-chen-0311',
  ownerPassword: process.env.PAYROLL_OWNER_PASSWORD,
  algorithm: 'aes-256',
  permissions: { modify: false, assemble: false, copy: false },
});

const plain = await decryptPdf(protectedCopy, 'mei-chen-0311');
```

`encryptPdf(bytes, options)` also accepts `password` for a file that is already encrypted, which is how you change a password or an algorithm. `decryptPdf(bytes, password?)` returns an unencrypted copy and passes plain input through unchanged.

On an open document, `pdf.encrypt(options)` and `pdf.decrypt()` set what the next `save()` does. That save is a full rewrite.

| `EncryptOptions` | Default | Meaning |
| --- | --- | --- |
| `userPassword` | `''` | Password to open the file. Empty means the file opens without a prompt but is still encrypted and carries its permissions. |
| `ownerPassword` | the user password | Password that grants every permission |
| `algorithm` | `'aes-256'` | `'rc4-40'`, `'rc4-128'`, `'aes-128'` or `'aes-256'` |
| `permissions` | all allowed | Any of `print`, `printHighQuality`, `modify`, `copy`, `annotate`, `fillForms`, `extractForAccessibility`, `assemble`; a flag you leave out is allowed |
| `encryptMetadata` | `true` | AES only. `false` leaves the XMP metadata readable without the password. |

| Algorithm | PDF revision | Notes |
| --- | --- | --- |
| `rc4-40` | 2 | Broken. Only for compatibility with very old readers. |
| `rc4-128` | 3 | Weak. Passwords are limited to 32 Latin-1 characters. |
| `aes-128` | 4 | Same password rules as RC4 |
| `aes-256` | 6 | Recommended. Unicode passwords, up to 127 bytes of UTF-8. Files with revision 5 can be opened as well. |

`permissionsToFlags()` and `permissionsFromFlags()` convert between the `PdfPermissions` object and the `/P` integer of the encryption dictionary.

### In the viewer

**Security** in the menu opens a dialog with the password to open, the password to change permissions, the algorithm (AES-256, AES-128 or RC4-128) and four permission switches: printing, changing the document, copying text and images, commenting and filling forms. **Remove protection** appears for an encrypted file. The change takes effect with the next save, and the document properties dialog shows the current encryption.

## Signing a protected file

A password-protected file can be signed and its signatures verified without removing the protection. Pass the password of the document:

```ts
import { signPdf, verifyPdfSignatures } from '@birchui/pdf/engine';

const signed = await signPdf(protectedBytes, {
  certificate: signerCertificatePem,
  privateKey: signerKeyPkcs8Pem,
  password: 'reader-2027',
});
const [result] = await verifyPdfSignatures(signed, { password: 'reader-2027' });
```

The signature is appended as an incremental update whose strings and streams are encrypted with the keys of the document; the signature value stays unencrypted, as the format requires. `addDocumentTimestamp` and `addValidationData` take the same `password` option. See [Signatures](https://docs.birchui.com/pdf/signatures.md#encrypted-documents).

## What permissions mean

A file opened with the user password (or with no password, when the user password is empty) is limited to what its permission flags allow. A file opened with the owner password has no limits. `pdf.encryption.isOwner` and `viewer.getEncryption()?.isOwner` say which password was used; `pdf.permissions` and `viewer.getPermissions()` report the flags, and `isAllowed(permission)` answers for one action.

| Permission | When it is denied |
| --- | --- |
| `print` | The print button, Ctrl+P and `viewer.print()` |
| `printHighQuality` | Printing above 150 dpi |
| `copy` | Copying and dragging text from the page, `getPageText`, `extractText`, `getTextRuns`, and merging the file into another document |
| `annotate` | Every annotation tool, editing, replying, deleting, XFDF and JSON import |
| `fillForms` | Filling in form fields. Allowed when either `fillForms` or `annotate` is granted. |
| `modify` | Watermark, header and footer, Bates numbers, crop, flatten, content editing, applying redactions, document properties, attachments, page labels and signing. Designing form fields needs `modify` and `annotate`. |
| `assemble` | Inserting, deleting, rotating, reordering, merging and extracting pages, and editing bookmarks. Allowed when either `assemble` or `modify` is granted. |

Changing or removing the protection needs the owner password as soon as any permission is denied. Saving is always allowed and keeps the encryption and the flags.

In the viewer, a control for a denied action stays visible, is marked `aria-disabled`, and its tooltip and accessible name say why, for example "Highlight. Not allowed by the security settings of this document: Commenting and filling forms". Activating it announces the same text. In the headless API, and in the viewer's own methods, a denied call throws a `PdfPermissionError` (or rejects with one) whose `permission` names the missing permission, and changes nothing:

```ts
import { PdfPermissionError } from '@birchui/pdf';
import { loadPdfDocument } from '@birchui/pdf/engine';

const pdf = await loadPdfDocument(statementBytes, { password: 'reader-2026' });
try {
  pdf.addWatermark({ text: 'COPY' });
} catch (error) {
  if (error instanceof PdfPermissionError) console.warn(`not allowed: ${error.permission}`);
  else throw error;
}
```

Permission flags are a request to the reading application, not a technical barrier: anyone with the user password can decrypt the whole file. For that reason there is an explicit way out, for services that are entitled to process the file:

```ts
const pdf = await loadPdfDocument(statementBytes, { password: 'reader-2026', ignorePermissions: true });
const viewer = createPdfViewer(container, { document: statementBytes, password, ignorePermissions: true });
```

With `ignorePermissions: true` nothing is blocked, `isAllowed()` returns `true` and `permissions` still reports the flags of the file. The option is read when a document is opened; changing it with `update()` takes effect with the next `load()`.

## Limits

- Certificate (public-key) encryption is not supported; such files fail with the reason `unsupported`.
- Optimizing an encrypted file with `optimizePdf` is refused. Decrypt first. To compare encrypted files, use `comparePdfAsync` with the passwords; see [Compare](https://docs.birchui.com/pdf/compare.md#password-protected-files).
- Encryption needs Web Crypto. Where it is missing (a page served over plain HTTP, for example) AES operations throw `PdfCryptoUnavailableError`.
- The password is kept in memory while the document is open, so the viewer can reload the document after a signature.
- The preview that the viewer gives to the renderer after a document tool is not encrypted. It exists only in memory.
- The permissions of the first document apply to the whole session. A protected document that is merged in is checked for `copy` only.

## Protect and permissions dialog

**Protect → Protect and permissions…** (`security`, also **Security** in the **Menu** button) sets the password to open, which has to be typed twice, the password to change permissions, the encryption (AES-256, AES-128, RC4-128) and one checkbox per permission: printing, high-quality printing, changing the document, page assembly, copying text and images, text access for screen readers, commenting, and filling in form fields. A mismatch between the two passwords or a missing password is reported in the dialog. On a protected document the boxes start from its current permissions and **Remove protection** is offered. The protection is written by the next save.
