C# Encrypt and Decrypt PDF file

Spire.PDF has a powerful function to encrypt and decrypt the PDF document with password. We have done some adjustments by the code to protect the PDF files. If you are using the Spire.PDF Version before 3.9.421, please refer to tutorial here for decrypt PDF, encrypt PDF in C#. From Spire.PDF v 3.9.421, you should use the new method offers in this article. This example shows how to protect and unprotect the PDF file with password using C# via the following two parts:

  • Encrypt PDF
  • Decrypt PDF

Encrypt PDF

There are two kinds of password for encrypt PDF, open password and modify password. The open password only sets to open the password. The modify password not only sets to open the PDF file, but also to set the restrictions of printing, contents copying, commenting and so on.

Spire.PDF offers pdf.Security.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) methods for us to encrypt the PDF file from opening, access permissions and set the PDF key size.

using Spire.Pdf;
using Spire.Pdf.Security;

namespace EncryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the document from file
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Sample.pdf");

            //encrypt the PDF file
            pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);

            //save the document to file
            pdf.SaveToFile("Encrypted.pdf", FileFormat.PDF);
        }
    }
}

C# Encrypt and Decrypt PDF file

Decrypt PDF

We need to load the encrypted PDF file with password (either open password or modify password is OK) by calling the method PdfDocument.LoadFromFile (string filename, string password). And then use the method of pdf.Security.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword) to reset the password or set the password as empty to decrypt the PDF file.

using Spire.Pdf;
using Spire.Pdf.Security;

namespace DecryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //use the open password to load the encrypted PDF file
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Encrypted.pdf", "open");

            //set the password as empty to decrypt PDF 
            pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");

            //save the document to file
            pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
        }
    }
}

C# Encrypt and Decrypt PDF file