Security

Security

This page covers passwords, encryption, and digital signatures. Document.OpenFile() / Document.Open() accept a password to open a protected document, Document.Save() accepts an encrypt option to protect one, and Document.Sign() / Document.Certify() / Document.VerifySignatures() add and check digital signatures.


Opening and Decrypting Password-Protected Documents

Pass { password: '...' } to Document.OpenFile() or Document.Open() to open a document protected with a user password. If the password is missing or wrong, the call throws InvalidPasswordError.

import { Document, InvalidPasswordError } from '@asposefoss/pdf';

try {
  const doc = Document.OpenFile('secret.pdf', { password: 'hunter2' });
  doc.WriteTo('decrypted.pdf');    // output is plaintext
} catch (e) {
  if (e instanceof InvalidPasswordError) console.error('wrong password');
  else throw e;
}

Encrypting on Save

Document.Save() (and Document.WriteTo()) accept an encrypt option. Password-based encryption is the common case; the library also supports public-key encryption to one or more recipient certificates, opened again with the recipient’s private key.

// Encrypt to one or more recipient certificates (PEM string or DER bytes):
const bytes = doc.Save({
  encrypt: {
    recipients: [{ certificate: recipientCertPem }],
    algorithm: 'aes256',                 // 'aes256' (default) | 'aes128' | 'rc4'
    permissions: { copying: false },     // shared across all recipients
  },
});

// Open with the recipient's private key + certificate, or a PKCS#12 bundle:
const opened = Document.Open(bytes, {
  recipient: { privateKey, certificate: recipientCertPem },
});
console.log(opened.Permissions);         // recovered permission flags (not enforced)

Signing and Certifying

Document.Certify() adds a certification (author) signature carrying a DocMDP transform that declares which later changes are permitted; Document.Sign() adds a further, ordinary approval signature that can be appended incrementally on top. Both take a { certificate, privateKey } signer and an options object (reason, location, name, fieldName, and — for Certify()permissions).

const certifying = Document.OpenFile('report.pdf');
await certifying.Certify(
  { certificate: author.certificate, privateKey: author.privateKey },
  { permissions: 'form-fill', reason: 'Certifying the report', fieldName: 'Certification' },
);
const certifiedBytes = certifying.Save();

const approving = Document.Open(certifiedBytes);
await approving.Sign(
  { certificate: approver.certificate, privateKey: approver.privateKey },
  { reason: 'Approved for publication', fieldName: 'Approval' },
);
approving.WriteTo('signed.pdf');

Verifying Signatures

Document.VerifySignatures() checks every signature in the document: it recomputes each /ByteRange digest, verifies the detached CMS, and reports what changed after each signature. It returns a SignatureReport[], one entry per signature.

const reports = await Document.OpenFile('signed.pdf').VerifySignatures();
for (const r of reports) {
  console.log(r.name, 'integrity:', r.integrity, 'signature:', r.signature);
}

Tips and Best Practices

  • Catch InvalidPasswordError specifically before a broader catch-all when opening untrusted input, so you can react differently to a bad password than to a corrupted file.
  • Call Certify() before any Sign() calls — a certification signature establishes the DocMDP permissions that later approval signatures are layered on top of.
  • Document.Open() returns recovered Permissions after public-key decryption, but the library does not enforce them itself — treat them as informational.
  • VerifySignatures() is asyncawait it (or handle the returned Promise) before reading the report array.

Common Issues

IssueCauseFix
Document.OpenFile() / Document.Open() throws InvalidPasswordErrorThe document is password-protected and no password, or the wrong one, was suppliedPass { password: '...' } to Document.OpenFile() / Document.Open()
Public-key decryption failsThe wrong private key or certificate was passed, or neither matches any recipients entry used at encryption timeConfirm the recipient option’s privateKey / certificate (or PKCS#12 bundle) matches one of the original recipients
An approval signature invalidates the certificationSign() was called with permissions the certifying DocMDP transform does not allowSet a permissions value on Certify() (e.g. 'form-fill') broad enough for the changes later signers will make
VerifySignatures() reports a broken integrity checkThe signed bytes were modified after signing, outside an incremental update the signature coversRe-sign the document after any further edits

FAQ

What is the difference between Sign and Certify?

Certify() adds the first, certification signature and declares (via a DocMDP transform) what later changes are permitted. Sign() adds an ordinary approval signature, appended incrementally on top of whatever came before it.

How do I open a password-protected PDF?

Pass { password: '...' } to Document.OpenFile() or Document.Open(), and catch InvalidPasswordError if the password might be wrong.

Does this library enforce PDF permission flags?

No. Document.Open() recovers the Permissions flags from an encrypted document for you to inspect, but does not itself restrict what your code can do with the opened document.

How do I check whether a signed PDF’s signatures are still valid?

Call Document.VerifySignatures() (an async method) and inspect each returned SignatureReport’s integrity and signature fields.


API Reference Summary

Class/MethodDescription
Document.OpenFile() / Document.Open()Open a document, optionally password- or public-key-protected
InvalidPasswordErrorThrown when a password is missing or wrong
Document.Save() / Document.WriteTo()Save a document, optionally with an encrypt option
PermissionsRecovered permission flags from an encrypted document
Document.Certify()Add a certification (author) signature with a DocMDP transform
Document.Sign()Add an approval signature
Document.VerifySignatures()Verify every signature in the document
SignatureReportOne signature’s verification result: name, integrity, signature

See Also