# Signatures

> Electronic signatures (drawn, typed, image) versus certificate signatures, signing with signPdf or viewer.signDocument using PKCS#8 keys, PKCS#12 files, a CryptoKey or an external signer, certification, several signatures, encrypted files, RFC 3161 timestamps, validation data (DSS), revocation checks, PAdES levels and the Signatures panel.

Birch UI PDF has two different things that are both called a signature.

| | Electronic signature | Certificate (digital) signature |
| --- | --- | --- |
| What it is | A drawn, typed or uploaded picture of a signature, stored as an annotation | A cryptographic signature over the bytes of the file, made with a private key and an X.509 certificate |
| How it is made | The Signature tool, a **Sign here** button in a signature field, `viewer.addSignature()` | `signPdf()`, `viewer.signDocument()`, **Sign document** in the menu |
| What it proves | Nothing by itself: anyone can place the same picture | That the holder of the key signed exactly these bytes, and whether they changed afterwards |
| Shown in | The Comments panel, like other annotations | The Signatures panel |

Electronic signatures are described under [Annotations](https://docs.birchui.com/pdf/annotations.md#electronic-signatures). The rest of this page is about certificate signatures.

Certificate signatures are created and validated without a server and without any dependency. ASN.1, X.509 and CMS are implemented in the package; hashing, signing and verification use Web Crypto, so the same code runs in browsers (on HTTPS or localhost), workers and Node 20 or later. `signPdf` and `verifyPdfSignatures` work on bytes, so they can run next to the viewer or in a backend job.

## Signing in the viewer

**Sign document**, in the menu and in the Signatures panel, asks for a certificate file and a private key file, both PEM, plus an optional reason and location, and whether to show the signature on the current page. The key must be an unencrypted PKCS#8 key (`BEGIN PRIVATE KEY`). It is read in the browser and is not sent anywhere. A PEM file with several certificates is used as the signer certificate followed by its chain.

For anything else, such as a key held by your server or a hardware token, call `signDocument` yourself:

```ts
const signed = await viewer.signDocument({
  certificate: signerCertificatePem,
  certificateChain: [intermediatePem],
  signDigest: async (digest) => {
    const response = await fetch('/api/signing/sign-digest', { method: 'POST', body: digest });
    return new Uint8Array(await response.arrayBuffer());
  },
  reason: 'Approved on behalf of Northwind Analytics Ltd',
  location: 'Manchester',
  field: { pageIndex: 11, rect: [320, 96, 540, 156] },
});
await fetch('/api/contracts/4471/file', { method: 'PUT', body: new Blob([signed], { type: 'application/pdf' }) });
```

`signDocument` takes the same options as `signPdf`. It first saves pending changes, signs the result, reloads the viewer with the signed file, emits `save`, opens the Signatures panel and resolves with the signed bytes. `name` defaults to the name of `currentUser`. It rejects when the document cannot be signed, for example in read-only mode or for an encrypted file. Signing is one undoable step. The document as it was before signing is kept with its undo history: **Undo** right after signing (the button reads **Undo signing**) brings that document back, unsigned, and the earlier steps can be undone as usual; **Redo signing** returns to the signed copy, byte for byte, as long as nothing else was done in between. Changes made after signing are undone first. The signed bytes already handed to `save` listeners are not affected. A file that was signed before it was opened has no such step: its signatures cannot be undone, only invalidated by a full rewrite, and the viewer asks before that.

## Signing

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

const signed = await signPdf(contractBytes, {
  certificate: signerCertificatePem,
  certificateChain: [intermediatePem],
  privateKey: signerKeyPkcs8Pem,
  reason: 'Approved by legal',
  location: 'Hamburg',
  contactInfo: 'legal@fabrikam.example',
  field: { name: 'approval', pageIndex: 0, rect: [320, 60, 560, 130] },
});
```

The result is the original file followed by one incremental update, so earlier signatures stay valid. The update holds an `adbe.pkcs7.detached` signature: a detached CMS `SignedData` with the signer certificate, the chain you passed, and the signed attributes content type, signing time, message digest and signing certificate (ESS v2). The `/ByteRange` covers the whole file except the signature string itself. With `subFilter: 'ETSI.CAdES.detached'` the signature follows the PAdES baseline profile instead: the same structure without the signing-time attribute, because PAdES keeps the time in the signature dictionary.

| Option | Meaning |
| --- | --- |
| `certificate` | Signer certificate, DER bytes or PEM text. RSA keys and ECDSA keys on P-256, P-384 or P-521 are supported. |
| `certificateChain` | Intermediate certificates to embed, DER or PEM (a PEM string may hold several). |
| `privateKey` | Unencrypted PKCS#8 PEM (`BEGIN PRIVATE KEY`) or a `CryptoKey` with the `sign` usage. |
| `signDigest` | External signer callback, used instead of `privateKey`. See below. |
| `pkcs12`, `pkcs12Password` | A `.p12` or `.pfx` file and its password, used instead of `certificate`, `certificateChain` and `privateKey`. See below. |
| `password` | The password of the document itself, when it is encrypted. See below. |
| `subFilter` | `'adbe.pkcs7.detached'` (default) or `'ETSI.CAdES.detached'` for a PAdES signature. |
| `timestamp` | Callback that returns an RFC 3161 timestamp token. See below. |
| `reason`, `location`, `contactInfo`, `name` | Written to the signature dictionary. `name` defaults to the certificate's common name. |
| `field` | Name of an existing empty signature field, or `{ name?, pageIndex, rect }` for a new visible field. Omit it for an invisible signature. |
| `appearance` | Options for the visible box, or `false` for an empty appearance. |
| `certify` | `'no-changes'`, `'form-filling'` or `'annotations-and-forms'` turns the signature into a certification signature (DocMDP). `certificationLevel: 1 \| 2 \| 3` is the same choice by number. |
| `signedAt` | Signing time. Defaults to now. |
| `placeholderSize` | Bytes reserved for the CMS message. The default fits the certificates plus 4 KB, and 12 KB more when `timestamp` is set. |

RSA signatures use PKCS#1 v1.5 with SHA-256 (or the hash of the `CryptoKey` you pass). ECDSA uses SHA-256 on P-256, SHA-384 on P-384 and SHA-512 on P-521. After signing, the signature is verified against the certificate, so a key that does not belong to the certificate fails immediately instead of producing a broken file.

Convert a PKCS#1 or SEC1 key with `openssl pkcs8 -topk8 -nocrypt -in key.pem -out key.pkcs8.pem`.

### Visible appearance

A new field with a non-empty `rect`, or an existing field with a widget, gets an appearance stream. By default it shows the signer name, the date in UTC, and the reason and location when present. The text shrinks to fit the box.

```ts
await signPdf(bytes, {
  certificate,
  privateKey,
  field: 'signature',
  appearance: {
    image: handwrittenSignaturePng,
    text: ['Priya Natarajan', 'General Counsel'],
    borderColor: null,
  },
});
```

`appearance` accepts `text` (replaces the default lines; an empty array shows only the image), `image` (PNG or JPEG, drawn on the left 40% or across the whole box when there is no text), `showDate`, `showReason`, `showLocation`, `fontSize`, `textColor`, `borderColor`, `borderWidth` and `backgroundColor`. Colours are RGB triples from 0 to 1. Text is drawn in Helvetica with Windows-1252 encoding; characters outside it show as `?`.

### HSM and remote signing

When the private key lives in an HSM, a smart card or a signing service, pass `signDigest` instead of `privateKey`:

```ts
declare const kms: { sign(request: { keyId: string; digest: Uint8Array; algorithm: string }): Promise<{ signature: Uint8Array }> };
declare const keyId: string;

const signed = await signPdf(bytes, {
  certificate: signerCertificatePem,
  signDigest: async (digest, info) => {
    const response = await kms.sign({ keyId, digest, algorithm: info.algorithm });
    return response.signature;
  },
});
```

- `digest` is the SHA-256 hash (32 bytes) of the DER-encoded signed attributes.
- `info.algorithm` is `RSASSA-PKCS1-v1_5` or `ECDSA`, chosen from the certificate's key. `info.hash` is `SHA-256`, `info.curve` is set for ECDSA, and `info.signedAttributes` holds the bytes that were hashed, for signers that need the message instead of the digest.
- For RSA, return the PKCS#1 v1.5 signature over that digest: the signer wraps the digest in a SHA-256 `DigestInfo`, pads and signs. This is what "sign digest" operations of HSMs and cloud key services do.
- For ECDSA, return either the raw `r || s` value or the DER `SEQUENCE { r, s }`. Both are accepted.

The package makes no network calls; the callback is the only place where one can happen.

### PKCS#12 files

```ts
import { signPdf, parsePkcs12, importPkcs12PrivateKey, Pkcs12Error } from '@birchui/pdf/engine';
declare function askForThePasswordAgain(): void;

const signed = await signPdf(bytes, {
  pkcs12: keyStoreBytes,
  pkcs12Password: 'Kontor 7 / Hafen',
  reason: 'Purchase order approved',
});

try {
  const contents = await parsePkcs12(keyStoreBytes, 'Kontor 7 / Hafen');
  const key = await importPkcs12PrivateKey(contents);
  console.info(contents.friendlyName, contents.chain.length, key.algorithm.name);
} catch (error) {
  if (error instanceof Pkcs12Error && error.reason === 'password-incorrect') askForThePasswordAgain();
}
```

`signPdf` takes the signer certificate, its chain and the private key from the file. `parsePkcs12(bytes, password)` returns `{ privateKey, privateKeyPem, certificate, chain, friendlyName? }`: the key as unencrypted PKCS#8 (DER and PEM), the certificate that belongs to it and the remaining certificates ordered from its issuer upwards. `importPkcs12PrivateKey(contents, hash?)` turns the key into a non-extractable `CryptoKey` for signing.

Files written by current tools (PBES2 with PBKDF2 and AES-128 or AES-256, integrity by HMAC-SHA-1, SHA-256, SHA-384, SHA-512 or PBMAC1) and by older ones (triple DES, 40-bit and 128-bit RC2, RC4, each with the PKCS#12 key derivation) are read, with empty and non-ASCII passwords. Triple DES and RC2 are not part of Web Crypto, so the package decrypts them itself. A wrong password, an unsupported algorithm and a damaged file throw `Pkcs12Error` with `reason` `'password-incorrect'`, `'unsupported'` or `'malformed'`. A file without an integrity check (`-nomac`) is accepted; a wrong password is then noticed when the contents do not decrypt.

### Encrypted documents

```ts
const signed = await signPdf(protectedBytes, {
  certificate,
  privateKey,
  password: 'reader-2027',
});
const results = await verifyPdfSignatures(signed, { password: 'reader-2027' });
```

A password-protected file (RC4, AES-128, AES-256) is signed in place: the strings and streams of the update are encrypted with the keys of the document, the signature value itself stays unencrypted as the format requires, and the protection is unchanged. Either the user or the owner password works. Without a password, or with a wrong one, `signPdf` and `verifyPdfSignatures` reject with `PdfPasswordError`. A session opened with a password passes it on, so `pdf.verifySignatures()` needs nothing extra.

### Timestamps

```ts
declare function requestTimestampToken(digest: Uint8Array): Promise<Uint8Array>;

const signed = await signPdf(bytes, {
  certificate,
  privateKey,
  timestamp: async (signatureValue, info) => requestTimestampToken(info.digest),
});
```

The callback receives the bytes to timestamp (here the signature value) and `info.digest`, their SHA-256 hash. Send the hash to your timestamp authority in an RFC 3161 request and return the DER response: either the `TimeStampToken` or the whole `TimeStampResp`. The token is checked before it is embedded, and a token issued for other data is refused with `PdfWriteError`. It is stored as the `id-aa-signatureTimeStampToken` unsigned attribute.

A document timestamp covers the whole file instead of one signature. It is what turns a signature with validation data into an archive signature, and it can be repeated before the certificate of the authority expires:

```ts
import { addDocumentTimestamp } from '@birchui/pdf/engine';
declare function requestTimestampToken(digest: Uint8Array): Promise<Uint8Array>;

const stamped = await addDocumentTimestamp(signed, {
  timestamp: async (fileBytes, info) => requestTimestampToken(info.digest),
});
```

`addDocumentTimestamp(bytes, { timestamp, fieldName?, placeholderSize?, password? })` appends an invisible signature field with a `/DocTimeStamp` of sub-filter `ETSI.RFC3161` as an incremental update. `placeholderSize` defaults to 16 KB.

### Certification signatures

`certify` adds a DocMDP transform and the catalog `/Perms` entry. It must be the first signature in the document.

| `certify` | Level | Changes permitted afterwards |
| --- | --- | --- |
| `'no-changes'` | `1` | Document timestamps and validation data only |
| `'form-filling'` | `2` | Filling forms and signing |
| `'annotations-and-forms'` | `3` | Filling forms, signing and annotating |

```ts
declare function showReadOnlyNotice(): void;

const certified = await signPdf(bytes, { certificate, privateKey, certify: 'form-filling' });

const pdf = openPdfDocument(certified);
if (pdf.certification?.permission === 'no-changes') showReadOnlyNotice();
```

A document opened in a session or in the headless API reports `certification` as `{ level, permission }`, or `undefined` when it is not certified, so an application can restrict editing before the user starts. `signPdf` refuses to add a signature to a document certified with `'no-changes'`.

### Several signatures

Call `signPdf` again on the signed bytes, with the name of an empty signature field or a new field. Each call appends another update, and earlier signatures keep verifying because their byte ranges are untouched. Validation reports for every signature what happened after it in `laterChanges`: `'none'` for the last one, `'signatures-only'` when later revisions added nothing but signatures, timestamps and validation data, `'allowed'` when they also contain permitted changes such as a filled form, and `'disallowed'` otherwise.

### Long-term validation

A signature can be checked years later only if the file itself carries the proof that the certificates were good when it was made. `addValidationData` stores that proof in the document security store (`/DSS`):

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

const longTerm = await addValidationData(signed, {
  certificates: [companyRootPem],
  fetch: async ({ certificate, ocspUrls, crlUrls }) => {
    const response = await fetch('/api/pki/revocation', {
      method: 'POST',
      body: JSON.stringify({ serial: certificate.serialNumber, ocspUrls, crlUrls }),
    });
    return { ocsp: new Uint8Array(await response.arrayBuffer()) };
  },
});
```

For every signature and timestamp in the file it builds the certificate chain from the certificates in the signature, in `certificates` and in an existing DSS, and looks for an OCSP response or a CRL for each certificate that has an issuer in the chain: first among `ocsps` and `crls` (DER bytes you already have), then by calling `fetch` with the certificate, its issuer and the OCSP and CRL addresses named in the certificate. The package does not contact these addresses itself. The result is one incremental update with `/Certs`, `/OCSPs`, `/CRLs` and a `/VRI` entry per signature, keyed by the SHA-1 hash of its `/Contents`; earlier signatures stay valid, and validation reports the update as `dss` changes. When there is nothing new to add, the input bytes are returned unchanged.

PAdES levels are reached step by step:

| Level | How to produce it |
| --- | --- |
| B-B | `signPdf` with `subFilter: 'ETSI.CAdES.detached'` |
| B-T | The same with a `timestamp` callback, or `addDocumentTimestamp` afterwards |
| B-LT | B-T, then `addValidationData` with revocation data for the signer's chain and the timestamp authority's chain |
| B-LTA | B-LT, then `addDocumentTimestamp` |

## Validation

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

const results = await verifyPdfSignatures(bytes, { trustedRoots: [companyRootPem] });
for (const signature of results) {
  console.info(signature.fieldName, signature.summary, signature.isTrusted, signature.modification.status);
}
```

Results are ordered by the revision they sign. Each one reports:

| Property | Meaning |
| --- | --- |
| `integrity` | `intact` when the digest of the signed byte ranges matches the signature, `modified` when it does not or the byte range does not bracket the signature string, `unsupported` when it cannot be checked. |
| `signature` | `valid` when the signature value verifies with the public key of the embedded signer certificate, otherwise `invalid` or `unsupported`. |
| `certificate` | Subject and issuer (full text plus common name, organization, unit, country, email), serial number, `notBefore`, `notAfter`, key algorithm and size, and the DER bytes. |
| `isCertificateValidAtSigning`, `isCertificateValidNow` | Whether the signing time and the current time fall inside the certificate's validity period. |
| `chain` | `status` and the certificates from signer to anchor. |
| `coversWholeFile` | Whether the signature covers everything up to the end of the file. |
| `modification` | What was appended after this signature. |
| `laterChanges` | `none`, `signatures-only`, `allowed`, `disallowed` or `unknown`: a summary of `modification` that tells later signatures apart from other permitted changes. |
| `type`, `certificationLevel`, `certification` | `signature`, `certification` (with the DocMDP level and its name) or `timestamp` (a document timestamp). |
| `signedAt`, `signedAtSource` | The signing time and whether it comes from a valid `timestamp`, the `signedAttribute` or the signature `dictionary`. |
| `timestamp` | For an embedded timestamp token: `time`, `authority`, `policy`, `serialNumber`, the `chain` of the authority with its `revocation` status, `isValid` and, when it is not valid, `error`. |
| `signingCertificate` | `matches` when the signing-certificate attribute names the certificate that signed, `mismatch` when it names another one, `absent` when there is no such attribute. |
| `revocation` | `good`, `revoked`, `unknown` or `not-checked` for the chain as a whole. Each entry of `chain.certificates` carries its own `revocation` and `revocationDetails`. |
| `padesLevel` | `B-B`, `B-T`, `B-LT`, `B-LTA` or `not-pades`. Not set for document timestamps. |
| `signerName`, `reason`, `location`, `contactInfo`, `subFilter`, `byteRange`, `digestAlgorithm`, `signatureAlgorithm` | Details from the signature dictionary and the CMS message. |
| `isValid` | `integrity` is `intact`, `signature` is `valid`, `modification.status` is `none` or `allowed`, `signingCertificate` is not `mismatch`, and no certificate of the chain was revoked before the signature provably existed. **It says nothing about who signed:** a certificate anyone made for themselves is `isValid`. |
| `isTrusted` | `isValid`, and the chain ends at one of your `trustedRoots`, the signer certificate was within its validity period at the signing time, it is not revoked, and an embedded timestamp, if there is one, is valid. This is the one to show a green tick for. |
| `summary` | One word for the interface: `trusted`, `valid-untrusted`, `changed-after-signing` (sound signature, disallowed later change), `revoked`, `invalid` or `unsupported`. |

### Changes after signing

Everything appended after a signature is compared, object by object, with the revision that was signed. A change is allowed only when the object had a role that may change:

| Kind | What it covers | Allowed after |
| --- | --- | --- |
| `signature`, `timestamp` | A new signature or document timestamp, its field, widget and appearance; signing an empty signature field that already existed | approval signature, `form-filling`, `annotations-and-forms` (timestamps also after `no-changes`) |
| `dss` | Validation data in the document security store | always |
| `form` | A new value and appearance for a field that is not locked; additions to the form's default resources | approval signature, `form-filling`, `annotations-and-forms` |
| `annotation` | New annotations with their appearances and popups, replies and review status on existing comments, new form fields, other edits to the properties of a field | approval signature, `annotations-and-forms` |
| `metadata` | The information dictionary and the XMP packet | approval signature, `form-filling`, `annotations-and-forms` |
| `appearance` | New objects nothing refers to | always |
| `other` | Everything else | never |

`other` is what makes a signature invalid. It includes any change to an object that the signed revision reached from a page's content, resources, fonts, images, patterns or shadings, from the page tree, the catalog, the outline, names, the structure tree or the form's default resources, whatever the object claims to be afterwards and whatever refers to it now; removed or reordered pages; a catalog entry other than the ones above; a changed signature dictionary; a field or widget that is hidden, moved or removed; a locked field; a cross-reference entry that points somewhere that does not hold the object it names; and bytes after the signed revision that are not a well-formed incremental update, such as objects appended without a cross-reference section. These are the published shadow attacks (hide, replace, hide-and-replace), incremental saving attacks and signature wrapping; each has a regression test.

The DocMDP level and the field locks are read from the revision that was signed, so a later revision cannot relax them. When either revision has a damaged cross-reference table the report is `unknown` and the signature is not valid.

### Annotations that cover content

After an approval signature the format allows new annotations, and an annotation's appearance can be an opaque rectangle with other text on it. Such a file stays `isValid`, because nothing the signer signed was changed, but it is reported:

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

declare const received: Uint8Array;

for (const signature of await verifyPdfSignatures(received)) {
  for (const warning of signature.warnings) console.warn(signature.fieldName, warning.code, warning.message);
  const covering = signature.modification.changes.filter((change) => change.coversContent);
  console.info(covering.map((change) => [change.pageIndex, change.coveredRatio]));
}
```

Every annotation that was added or changed after the signature carries `pageIndex`, `coveredRatio` (the share of the area of the page's text, as the signer saw it, that lies under the annotation's rectangle; the page itself when it has no text) and `coversContent`, which is true when that share is above half a percent and the appearance fills, shades or draws an image without reduced opacity. Text markup, sticky notes, links and translucent shapes do not count. `warnings` on the result and on `modification` has one `annotation-covers-content` entry per such annotation, and the signatures panel of the viewer shows "An annotation added after signing covers page content". Decide in your application whether that is acceptable; certify with `form-filling` if annotations should not be possible at all.

### Locking fields

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

declare const contract: Uint8Array;
declare const keyStore: Uint8Array;

const signed = await signPdf(contract, {
  pkcs12: keyStore,
  pkcs12Password: 'correct horse battery staple',
  field: 'signature',
  lockFields: { include: ['client.name', 'fee'] },
});
console.info(signed.length);
```

`lockFields` is `'all'`, `{ include: [...] }` or `{ exclude: [...] }` with fully qualified field names; a name also covers the fields below it. The lock is written to the signature field (`/Lock`) and to the signature as a FieldMDP transform. A signature field that already carries a `/Lock` dictionary is honoured without the option. When a document is verified, any change to a locked field after that signature is `other`. A `/P` entry in a lock dictionary lowers the permission level for later changes the way a certification does.

Supported formats are `adbe.pkcs7.detached`, `ETSI.CAdES.detached`, `adbe.pkcs7.sha1`, `adbe.x509.rsa_sha1` and `ETSI.RFC3161`, with RSA PKCS#1 v1.5, RSA-PSS and ECDSA (P-256, P-384, P-521) over SHA-1, SHA-256, SHA-384 or SHA-512.

### Chain status

The chain is built from the certificates inside the signature and checked against `trustedRoots` (DER or PEM). Every link's signature is verified.

| Status | Meaning |
| --- | --- |
| `trusted` | The chain ends at one of your roots, or the signer certificate itself is one of them. |
| `untrusted` | The chain is complete but ends at a root you did not supply. |
| `self-signed` | The signer certificate is self-signed and not among your roots. |
| `incomplete` | An issuer is missing from the signature and from your roots. |

### Timestamps

A timestamp token is valid when it was issued for exactly the signed data (the signature value for a signature timestamp, the byte range for a document timestamp), the timestamp information matches the digest the authority signed, the signature of the authority verifies, a signing-certificate attribute names the certificate that signed, and that certificate carries the timestamping extended key usage and was within its validity period at the time of the token. The chain of the authority is built against `trustedRoots` like any other and reported in `timestamp.chain` (for a document timestamp, in `chain`). A valid timestamp sets `signedAt`; an invalid one is reported with `error` and ignored.

### Revocation

```ts
declare function lookUpRevocation(
  serialNumber: string,
  issuer: string,
): Promise<{ isRevoked: boolean; revokedAt?: Date; reason?: string }>;

const results = await verifyPdfSignatures(bytes, {
  trustedRoots: [companyRootPem],
  ocsps: [ocspResponseBytes],
  crls: [crlBytes],
  checkRevocation: async (certificate, issuer) => {
    const status = await lookUpRevocation(certificate.serialNumber, issuer.subject.text);
    return status.isRevoked ? { status: 'revoked', revokedAt: status.revokedAt, reason: status.reason } : { status: 'good' };
  },
});
for (const certificate of results[0].chain.certificates) {
  console.info(certificate.subject.commonName, certificate.revocation, certificate.revocationDetails?.revokedAt);
}
```

For every certificate of the chain that has its issuer in the chain, revocation data is taken from the DSS of the document, from revocation data inside the signature (the Adobe revocation attribute and CRLs in the CMS message), then from `ocsps` and `crls`, and finally from `checkRevocation`. The last certificate of a chain, a trust anchor or a root, is `not-checked`.

An OCSP response counts when it names the certificate (issuer name hash, issuer key hash and serial number) and is signed by the issuer or by a responder certificate that the issuer issued with the OCSP-signing extended key usage. A CRL counts when it is a complete CRL issued and signed by the issuer of the certificate. Data that fails these checks is ignored. Data is current when its `thisUpdate` is not in the future and its `nextUpdate` is not before the reference time: the time of a valid signature timestamp or of a later valid document timestamp, otherwise now. A `good` answer that is no longer current is reported as `unknown`.

| `revocation` | Meaning |
| --- | --- |
| `good` | Every checked certificate has a current `good` answer |
| `revoked` | At least one certificate is revoked; `revocationDetails` holds `revokedAt`, `reason` and the `source` (`ocsp`, `crl` or `callback`) |
| `unknown` | There is data, but it is not current, says `unknown`, or covers only part of the chain |
| `not-checked` | No data for any certificate and no callback |

A revoked certificate makes the signature invalid unless a valid timestamp proves that the signature existed before the revocation time. Without a timestamp the signing time is only a claim, so any revocation fails the signature. `unknown` and `not-checked` do not change `isValid`, unless you pass `requireRevocation: true`.

### PAdES level

`padesLevel` describes what the file contains, independent of trust: `B-B` for an `ETSI.CAdES.detached` signature whose signing-certificate attribute matches, `B-T` when a valid signature timestamp or a later document timestamp exists, `B-LT` when the DSS or the signature holds verifiable revocation data for every certificate of the signer's chain and of the timestamp authority's chain, and `B-LTA` when a later valid document timestamp covers a revision whose DSS already held that data. Other signatures are `not-pades`. For B-LT the chains must be complete, so add the root with `certificates` in `addValidationData` when the signature does not embed it.

### Changes after signing

When bytes follow a signature, the signed revision is compared with the current one object by object, and every difference is classified:

| Kind | Examples |
| --- | --- |
| `form` | Field values, new fields and widgets, the AcroForm dictionary |
| `annotation` | Added, edited or removed annotations |
| `signature` | Later signatures, signed signature fields, `/Perms` |
| `timestamp` | Document timestamps and their fields |
| `dss` | Document security store with validation data |
| `appearance` | New appearance streams and other new supporting objects |
| `metadata` | The document information dictionary and XMP metadata |
| `other` | Page content, the page tree, page boxes and rotation, catalog entries, changed fonts or images |

`modification.status` is `none` when the signature covers the whole file, `allowed` when every change is permitted, `disallowed` otherwise and `unknown` when the signed revision cannot be parsed. Without a certification signature everything except `other` is permitted. With one, the level decides: level 1 permits `timestamp`, `dss` and `appearance`; level 2 adds `signature`, `form` and `metadata`; level 3 adds `annotation`. `modification.changes` lists the object number, whether it was added, changed or removed, and the kind.

## The Signatures panel

The Signatures panel lists every signed field of the open document, oldest first, with a headline:

| Headline | When |
| --- | --- |
| Signature is valid | Digest and signature verify and nothing was changed afterwards. Shown as trusted only when the chain ends at one of your `trustedCertificates`; otherwise the entry is marked as a warning and says that the signer could not be traced to a trusted certificate, or that the certificate is self-signed. |
| Signed, with later changes that the signature allows | The signature verifies and every later change is of a permitted kind |
| The document was changed after signing | The signed bytes changed, the signature value is wrong, or a later change is not permitted |
| Signature could not be verified | The format or algorithm is not supported |

Each entry also shows the signer, the signing time, reason, location, issuer, algorithm and the kinds of later changes; clicking it scrolls to the signature field. **Verify again** repeats the check.

```ts
viewer.update({ trustedCertificates: [northwindRootPem, fabrikamRootPem] });

const results = await viewer.verifySignatures();
const allGood = results.length > 0 && results.every((r) => r.isTrusted);
```

`viewer.verifySignatures()` validates the file as it was opened, with `trustedCertificates` as the trust roots. The headless `pdf.verifySignatures({ trustedRoots, now, ocsps, crls, checkRevocation, requireRevocation })` and `verifyPdfSignatures(bytes, options)` do the same; `verifyPdfSignatures` also takes `password` for an encrypted file. `getSignatures()` is the older, lighter call: it reports the signer, time, byte range and a digest check for each signature field, without certificate checks.

## PEM helpers

`pemToDer(pem, label?)`, `derToPem(der, label)`, `pemBlocks(pem, label)` and `certificateToDer(input)` convert between PEM text and DER bytes, for example to split a certificate bundle before you pass it as `certificateChain`.

## Trust lists and chain constraints

A host that distributes its trust anchors as a list can give the list an expiry date. `loadTrustList` reads the list (an object or JSON text), and verification uses its certificates as trusted roots until that date:

```ts
import { loadTrustList, openPdfDocument } from '@birchui/pdf/engine';

const anchors = loadTrustList(await (await fetch('/trust/fabrikam-anchors.json')).text());
const pdf = openPdfDocument(new Uint8Array(await (await fetch('/files/msa-signed.pdf')).arrayBuffer()));
const [result] = await pdf.verifySignatures({ trustLists: [anchors] });
if (result.expiredTrustLists) console.warn('fetch the trust list again:', result.expiredTrustLists);
```

The list is `{ name, expires, issued?, certificates }`, with certificates as PEM text or DER bytes. `loadTrustList` throws for a list without a name, an expiry date or a certificate array; a certificate that cannot be read is counted in `rejected` and left out. A list past its expiry date is not used: its roots anchor nothing, the chain is reported as it is without them, and the name of the list is in `expiredTrustLists` of every result. The viewer takes the lists as the `trustLists` option and names an expired list in the Signatures panel. The package does not download lists and does not check a signature on the list itself; fetch it over a channel you trust.

Beyond signatures and revocation, a chain is checked against the constraints its certificates carry (RFC 5280, section 6). `chain.problems` lists what is broken, each with a `code`, the position of the certificate in the chain, its subject and a sentence:

| Code | Meaning |
| --- | --- |
| `key-usage` | The signing certificate has a key usage extension without `digitalSignature` and `nonRepudiation`, or an issuer has one without `keyCertSign` |
| `not-a-ca` | A certificate that issued another one is not marked as a certificate authority |
| `path-length` | More CA certificates follow a CA than its path-length limit allows |
| `name-constraints` | An e-mail address, DNS name or subject of a certificate is excluded, or not among the permitted names, of a CA above it |
| `ca-not-valid-at-signing` | An issuer was not within its validity period at the time of signing |

A signature whose chain has a problem keeps `signature: 'valid'` and `integrity: 'intact'` when its mathematics is sound, but `isTrusted` is `false`, `summary` is `'valid-untrusted'`, `error` holds the first sentence, and the panel shows a warning with it. `checkChainConstraints(chain, at)` is exported for chains you build yourself. Not checked: certificate policies and policy constraints, IP address and URI name constraints, and unknown critical extensions.

## Limits

- There is no built-in RFC 3161, OCSP or CRL client and no network access: you fetch timestamp tokens in the `timestamp` callback and revocation data in the `fetch` and `checkRevocation` callbacks.
- Revocation checking covers OCSP responses signed by the issuer or by a responder it delegated, and complete CRLs signed by the issuer of the certificate. Indirect CRLs, delta CRLs, partitioned CRLs (issuing distribution points) and responders trusted by local configuration are not supported. The revocation status of an OCSP responder certificate is not checked.
- Certificate policies, name constraints, key usage and path-length constraints are not enforced. A `trusted` chain means every link is correctly signed and ends at one of your roots. Validity periods of intermediate certificates are not checked; only the signer certificate is checked against the signing time and the current time.
- `padesLevel` reports the structure of the file. It is not a conformance statement: signature policies, the algorithm constraints of ETSI EN 319 142 and the validation procedure of ETSI EN 319 102 are not applied.
- Timestamp tokens must carry a signing-certificate attribute that does not contradict the signer, and the authority certificate must have the timestamping extended key usage. Whether that usage is marked critical and whether it is the only usage is not checked. Timestamp accuracy and nonces are not evaluated.
- A signature field that is already signed, the widget of such a field, and any annotation that existed when the document was signed may not be hidden, moved, restyled or removed afterwards; such an edit counts as a disallowed change even without certification. A signature appearance that covers page content is not detected: at `form-filling` and above a later signer chooses what their own signature field looks like.
- Public-key (certificate) encrypted documents cannot be signed or verified, because they cannot be opened.
- PKCS#12 files protected with a public key instead of a password are not read, and neither are files whose key is not RSA or ECDSA on P-256, P-384 or P-521. The pure TypeScript triple DES and RC2 code is not constant-time; it only decrypts key stores with a password the caller supplies.
- Encrypted PKCS#8 keys and PKCS#1 or SEC1 keys are not read. Convert to an unencrypted PKCS#8 PEM, use a PKCS#12 file, import the key as a `CryptoKey`, or use `signDigest`.
- Ed25519, Ed448 and DSA keys are reported as `unsupported`.
- The visible appearance is not rotated on pages with a `/Rotate` entry.
- A full rewrite of a signed file (page changes, applied redactions, encryption changes, optimizing) invalidates its signatures. See [Saving](https://docs.birchui.com/pdf/saving.md#full-rewrites).
