PDF Security: Encrypt or Decrypt PDF Files in C# .NET

In today's digital landscape, PDFs carry sensitive contracts, financial reports, and personal data. A single breach can lead to compliance violations or intellectual property theft. To protect your PDFs from unauthorized access, it’s necessary to encrypt them.

Visual guide for Encrypt PDF or Decrypt PDF in C#

Spire.PDF for .NET provides enterprise-grade PDF security solution, enabling developers to easily implement PDF encryption/decryption workflows in .NET applications. This article will provide practical examples to show you how to use C# to encrypt PDF or decrypt PDF.

.NET Library for PDF Security

Why Use Spire.PDF?

Spire.PDF is a robust, standalone .NET library designed to create, edit, convert and secure PDF documents without Adobe Acrobat. Speaking of its security features, it enables developers to:

  • Apply AES/RC4 encryption with password protection
  • Restrict printing/copying/editing permissions
  • Support .NET Framework, ASP.NET Core, and .NET 5+

Installation Guide

Method 1: NuGet Package Manager (Recommended)

  • Open your project in Visual Studio
  • Go to “Tools -> NuGet Package Manager -> Package Manager Console”
  • Run the following:
PM> Install-Package Spire.PDF

Method 2: Manual Installation

  • Download DLL from Spire.PDF Official Site
  • Right-click your project in Solution Explorer
  • Go to “Add-> Reference -> Browse -> Select Spire.PDF.dll”.

What is Involved in PDF Encryption?

Spire.PDF allows developers to encrypt PDF with passwords, set encryption algorithm, and set permissions. Below is a comprehensive technical breakdown:

User & Owner Passwords

  • User Password (Open Password): Required to open and view the PDF.
  • Owner Password (Permissions Password): Controls security permissions (printing, copying, editing)

Critical Security Rule: The owner password overrides user password restrictions. If a PDF file is encrypted with both passwords, it can be opened with either one. PDF password access flow

Example code:

PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(
"user123",   // Open password
"e-iceblue"   // Permission password
);

Encryption Algorithms (RC4 and AES Encrypt)

Spire.PDF supports industry-standard encryption methods with varying key strengths:

Algorithm Key Length Security Level Use Case
AES 128/256-bit Military-grade Sensitive documents (Default)
RC4 40/128-bit Legacy Backward compatibility

Example code:

securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;

Permission Flags

Permission flags control user actions on encrypted PDF documents after opening. These flags are controlled via the properties of the PdfDocumentPrivilege class. Here are some common permission flags.

Properties Description
AllowContentCopying Gets or sets the permission which allow copy contents or not.
AllowPrint Gets or sets the permission which allow print or not.
AllowModifyContents Gets or sets the permission which allow modify contents or not.
AllowFillFormFields Gets or sets the permission which allow fill in form fields or not.
AllowAll All allowed.
ForbidAll All forbidden.

Example code:

securityPolicy.DocumentPrivilege.AllowPrint = false;  // Disable printing
securityPolicy.DocumentPrivilege.AllowContentCopying = false;  // Disable copying

How to Encrypt a PDF in C# (Code Example)

The following C# code password protects a PDF file with AES-256 encryption and restrict permissions.

using Spire.Pdf;

namespace EncryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            // Load a sample PDF file
            pdf.LoadFromFile("sample.pdf");

            // Specify the user and owner passwords
            string userPassword = "user123";
            string ownerPassword = "e-iceblue";

            // Create a PdfSecurityPolicy object with the two passwords
            PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(userPassword, ownerPassword);

            // Set encryption algorithm
            securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;

            // Set document permissions (If you do not set, the default is ForbidAll)
            securityPolicy.DocumentPrivilege = PdfDocumentPrivilege.AllowAll;

            // Restrict printing and content copying
            securityPolicy.DocumentPrivilege.AllowPrint = false;
            securityPolicy.DocumentPrivilege.AllowContentCopying = false;

            // Encrypt the PDF file 
            pdf.Encrypt(securityPolicy);

            // Save the result file
            pdf.SaveToFile("EncryptPDF.pdf", FileFormat.PDF);
        }
    }
}

The encrypted PDF will:

  • Require a password to open.

Encrypt a PDF file with passwords

  • Block printing and copying content. Retain all other permissions (editing, form filling, etc.).

Set PDF permissions to restrict printing and copying

How to Decrypt a PDF in C# (Steps & Code)

Decrypt PDF removes passwords and restrictions, allowing full access to the document. With Spire.PDF, you can decrypt a password-protected PDF file in C# with <5 lines of code.

Main Steps:

  • Open Encrypted PDF: Load your encrypted PDF file with the owner password.
  • Remove Encryption: Invoke the Decrypt() method to remove all security restrictions.
  • Save Decrypted PDF: Call the SaveToFile() method to save the decrypted PDF to the specified file path.

Code Example:

The following C# code removes the PDF passwords and restores access.

using Spire.Pdf;

namespace DecryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            // Load a sample PDF file with owner password
            pdf.LoadFromFile("EncryptPDF.pdf", "e-iceblue");

            // Decrypt the PDF file
            pdf.Decrypt();

            // Save the Decrypted PDF
            pdf.SaveToFile("DecryptPDF.pdf");
        }
    }
}

Open the decrypted PDF:

Remove passwords to decrypt PDF

Conclusion

Securing PDFs with encryption is essential for protecting sensitive data. With Spire.PDF for .NET, developers can effortlessly encrypt, decrypt, and manage permissions in PDF files using C#. The .NET PDF library’s comprehensive features and straightforward implementation make it an ideal choice for enhancing document security in enterprise applications.

Next Steps:

FAQs

Q1: Can I encrypt a PDF without a user password?

A: Yes. Set the user password to an empty string and use the owner password to control permissions.

Q2: What encryption standards are supported?

A: Spire.PDF supports:

  • 40-bit RC4 (legacy)
  • 128-bit RC4/AES (standard)
  • 256-bit AES (highest security)

Recommend 256-bit AES for sensitive data compliance (e.g., HIPAA, GDPR).

Q3: How to handle incorrect passwords when decrypting?

A: Use try-catch blocks to handle exceptions:

try
{
    pdf.LoadFromFile("EncryptPDF.pdf", " wrongPassword");

}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Q4. How to check if a PDF is encrypted?

A: Use the PdfDocument.IsPasswordProtected(string fileName) method. A comprehensive guide can be found at: Check Whether a PDF is Password Protected in C#