PDF encryption is built into the file format. The writer encrypts every string and stream inside the file, and readers ask for a password before they decrypt anything. To password protect PDF files in C#, you need a PDF library, not raw System.Security.Cryptography calls. For new files, use AES-256 (security handler revision 6, defined in ISO 32000-2). Set both a user password and an owner password, and remember that only the reader enforces permission flags. Xceed PDF Library for .NET (NuGet: Xceed.PdfLibrary.NET 3.1) provides EncryptionOptions and EncryptionProfile types. It reports encrypted input through PdfDocument.IsEncrypted and throws InvalidPasswordException for bad passwords. Keep passwords out of source code, and never encrypt PDF/A archives.
Contracts, payslips, medical reports and invoices all leave your servers as PDF files. Once a file lands in an inbox or a shared drive, the only protection it carries is what the file itself contains. For that reason, teams that generate documents eventually need to password protect PDF files in C#, not only secure the transport channel.
The requirement sounds small. However, it raises real design questions: which algorithm, which passwords, which permissions, and where the passwords live. Wrong answers produce files that either open for anyone or refuse to open for the people who need them.
This guide explains how PDF encryption works at the format level and why AES-256 is the default to choose. It then walks through the workflow with Xceed PDF Library for .NET. All of the code targets the shipped Xceed.PdfLibrary.NET 3.1 API.
How PDF Encryption Works
PDF encryption lives inside the file format. Specifically, the PDF standard security handler encrypts every string and stream object, including page content, images and embedded metadata. Meanwhile, the document skeleton stays readable, so the cross-reference table and trailer remain plain bytes. As a result, a reader can open the container, find the encryption dictionary, and ask for a password before it decrypts any content.
This design has a direct consequence for .NET developers. Because encryption touches every object, the PDF writer applies it during serialization, object by object. You therefore cannot bolt it on afterwards with a generic file encryptor and still end up with a valid PDF.
User passwords and owner passwords
- User password: Sometimes called the open password, readers require it to decrypt and display the document.
- Owner password: Grants full access and authorizes changes to the permission flags.
Permission flags cover printing, content copying, modification, annotations, form filling, page assembly and accessibility extraction. Additionally, you can set an owner password with an empty user password. In that case anyone can open the file, and the flags only limit what a compliant reader allows.
Why AES-256 PDF encryption is the right default
PDF security has gone through several algorithm generations. Early PDF versions used 40-bit RC4. PDF 1.4 raised RC4 keys to 128 bits, and PDF 1.6 added AES-128. Adobe then introduced AES-256 as an extension to PDF 1.7. Later, the ISO 32000-2 (PDF 2.0) specification standardized AES-256 with security handler revision 6. It also deprecated RC4 and the earlier revision 5 key derivation.
Recommended encryption standard
For new documents, AES-256 PDF encryption is the sensible default. RC4 has known cryptographic weaknesses, and 40-bit keys fall to brute force on ordinary hardware. Choose AES-128 only when a documented reader requirement forces it.
Why Raw .NET Cryptography Is the Wrong Tool
.NET ships excellent cryptographic primitives. For example, the System.Security.Cryptography.Aes class on Microsoft Learn encrypts any byte array with a 256-bit key. However, if you encrypt a whole PDF file this way, you get an opaque blob. Acrobat, browsers and mobile viewers cannot open that blob, and recipients have nowhere to type a password.
A common workaround is to place the PDF in a password-protected ZIP archive. That approach protects the file in transit, yet the extracted PDF carries no protection once it sits on disk. Similarly, some teams try to write their own PDF security handler on top of the Aes class. Revision 6 key derivation uses an iterated SHA-256, SHA-384 and SHA-512 hash loop. Strings, streams and metadata also each need separate handling. Small mistakes produce files that open in one viewer and fail in another.
The .NET base class library has no PDF API at all. So the practical path is a PDF library that implements the security handler and writes the encryption dictionary for you.
How to Password Protect PDF Files in C# with Xceed PDF Library
Xceed PDF Library pour .NET is a managed library for creating, reading and editing PDF documents. Beyond encryption, the same PdfDocument class handles merging, splitting, text search and replacement, form fields, attachments, digital signatures and PDF/A validation. Consequently, security becomes one step in your existing document pipeline instead of a separate tool.
Version 3.1 (package version 3.1.26464.8460) also added the SaveOptions.Standards and SaveOptions.Language properties, plus PdfDocument.ValidatePdfStandard. Those additions matter later in this guide, because PDF/A and encryption interact.
A reader prompts for the user password before it decrypts an AES-256 protected PDF.
Install the NuGet package
Add the Xceed.PdfLibrary.NET package on NuGet to your project. The public API lives in the Xceed.PdfLibrary.NET namespace, while drawing primitives sit in Xceed.Drawing.
NuGet Installation
Set the license key
The library reads its license from code. Set the key once at application startup, before you load or create any document. No online activation is involved, so build agents and air-gapped servers behave the same way. During evaluation, use the key from the 45-day free trial.
License Configuration
Detect encrypted input files
Check what you received before you add protection. Upstream systems sometimes send files that are already encrypted, and processing them without the original password fails. The IsEncrypted property reports the current state. Meanwhile, InvalidPasswordException signals a missing or wrong password.
Inspect PDF Encryption
API note: PdfDocument.Load has no single-argument overload. Both overloads, one for a file path and one for a Stream, take a LoadOptions instance as the second parameter.
Write the password-protected file
The writer applies encryption when it saves the document. Xceed PDF Library has two dedicated types for these settings, EncryptionOptions and EncryptionProfile. Typical settings include the user password, the owner password, the algorithm and the permission set. The skeleton below shows the save pipeline that the encryption configuration plugs into. Member names can change between releases, so check the EncryptionOptions reference for the version you install. Choose the AES-256 profile whenever your target readers support it.
PDF Encryption Save Pipeline
Important: This example is a save pipeline skeleton. It does not encrypt the output until the encryption options have been configured.
After configuring encryption and saving, open the output in at least two readers. Confirm that the password prompt appears and that the correct password opens the file. Finally, verify that restricted actions such as printing or copying stay disabled.
Encrypt PDF in C# for Production Workloads
A demo that writes one file is easy. However, code that runs thousands of times a day needs proper handling for secrets, streams and signatures before you encrypt PDF files in C# at scale.
Keep passwords out of source code
Hard-coded passwords end up in Git history, build logs and decompiled assemblies. Instead, load them at runtime. During development, ASP.NET Core user secrets keep values out of the repository. In production, a vault such as Azure Key Vault stores and rotates them. A small helper fails fast when configuration is missing:
Secure Password Configuration
Per-recipient passwords deserve the same care. For example, a payroll system might base each user password on data the employee already knows, then send the hint through a separate channel. Never put the password in the same email as the attachment.
Return encrypted PDFs from ASP.NET Core
Web APIs rarely write to disk. The SaveAs(Stream, SaveOptions) overload writes directly to a stream, so a controller can return the bytes with File(bytes, "application/pdf").
Save PDF to a Memory Stream
Combine encryption with digital signatures
Encryption and signatures solve different problems. Encryption controls who can read a document, while a signature proves who produced it and that nobody changed it. Xceed PDF Library signs through PdfDocument.Sign, which accepts a SignatureFormField, an ISigningCredential and SignatureOptions. Credential types include PfxSigningCredential and StoreSigningCredential. Additionally, ValidateSignatures returns a SignatureValidationResult array for verification. When a workflow needs both, test the combined output in each target reader, since viewer support for signed and encrypted files varies.
Practical Tips and Common Pitfalls
PDF Encryption Best Practices
- Do not encrypt PDF/A archives: Every part of PDF/A forbids encryption, since archival files must stay readable without keys decades later. If you produce PDF/A, keep the unencrypted master in access-controlled storage and distribute encrypted copies. Before archiving, run ValidatePdfStandard on the master to confirm conformance.
- Treat permissions as policy, not protection: Permission flags depend on reader compliance. Major viewers respect them; however, some tools ignore them once the file is open. Therefore, rely on the user password and your access controls for confidentiality, and use permissions to express intent.
- Choose strong user passwords: AES-256 only helps when the password resists guessing. An attacker can test guesses against a copied file offline with no rate limits. As a result, short or predictable passwords such as birth dates fall quickly. For automated distribution, generate long random passwords instead.
- Log state, never secrets: Record the encryption state, the profile you chose and the document ID in your logs. Never log the password, even at debug level, because log stores usually have wider access than document stores.
When to choose which library
Alternatives in this space include Aspose.PDF for .NET, which covers a very broad PDF feature set, and Syncfusion's PDF library, which pairs well with its UI component suites. IronPDF focuses on HTML-to-PDF rendering, while PDFsharp is an MIT-licensed open-source option. Pick based on the rest of your document pipeline, your licensing model and your support needs. For more document-processing guides, browse the Xceed blog.
Essayez Xceed PDF Library pour .NET
Build password-protected PDF workflows in C# with a 45-day free trial, no credit card required.
Foire aux questions
How do I password protect a PDF file in C#?
Use a PDF library that implements the PDF standard security handler, because raw AES calls produce a file that PDF readers cannot open. With Xceed PDF Library for .NET, you load or create a PdfDocument, configure encryption through the EncryptionOptions and EncryptionProfile types, and write the file with SaveAs.
What is the difference between a user password and an owner password in a PDF?
Readers require the user password to open and decrypt the document. The owner password unlocks full access and lets the holder change permissions. A file with only an owner password opens for anyone, so the user password is the real confidentiality barrier.
Is AES-256 PDF encryption supported by all PDF readers?
Current versions of mainstream readers support AES-256 as defined in ISO 32000-2. Older or embedded viewers may only handle RC4 or AES-128. Test encrypted output in the readers your recipients actually use before rolling it out.
Can a PDF/A document be encrypted?
No. Every PDF/A part prohibits encryption, because archival files must stay readable without keys. Keep an unencrypted PDF/A master in a secured store and distribute encrypted copies, and validate the master with PdfDocument.ValidatePdfStandard before archiving.
Do PDF permission flags stop people from copying or printing?
Compliant readers honor them, but the flags are not cryptographic barriers once a user opens the file, and some tools ignore them. Treat permissions as policy signals and rely on the user password and access control for confidentiality.
Does Xceed PDF Library need an internet connection for licensing?
No. You set the license key in code through the Licenser class. There is no online activation and no phone-home, so builds and applications run on offline or air-gapped machines.