PDF Encryption in C# and VB.NET

PDF encryption is a security mechanism used when:

  • You want only certain people (for example, those that know the password) to view your PDF.
  • You don’t want anyone to print or edit your PDF (enforced by PDF viewer/editor application).

With GemBox.Pdf, you can perform the following PDF encryption scenarios in your C# or VB.NET application:

The following examples demonstrate each of those scenarios.

Encrypt a PDF file

The following example shows how to encrypt an existing PDF file with a password.

Screenshot of PDF file encrypted using GemBox.Pdf
PDF file encrypted using GemBox.Pdf
Upload your file (Drag file here)
using GemBox.Pdf;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Load PDF document from an unencrypted PDF file.
        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Set password-based encryption with password required to open a PDF document.
            document.SaveOptions.SetPasswordEncryption().DocumentOpenPassword = "%DocumentOpenPassword%";

            // Save PDF document to an encrypted PDF file.
            document.Save("Encryption.pdf");
        }
    }
}
Imports GemBox.Pdf

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        ' Load PDF document from an unencrypted PDF file.
        Using document = PdfDocument.Load("%InputFileName%")

            ' Set password-based encryption with password required to open a PDF document.
            document.SaveOptions.SetPasswordEncryption().DocumentOpenPassword = "%DocumentOpenPassword%"

            ' Save PDF document to an encrypted PDF file.
            document.Save("Encryption.pdf")
        End Using
    End Sub
End Module

As shown in the screenshot from above, the output PDF file has a Password Security method and Document Open Password is required to open a PDF file.

User can perform all operations except page extraction. The Restrict Editing example shows how to modify user access permissions.

Encryption level is 128-bit AES and is supported in Adobe Acrobat 7.0 and later. All contents of the document are encrypted, including metadata (used by search engines). The Encryption Settings example shows how to modify the encryption level and options.

Decrypt a PDF file

The following example shows how to decrypt a password-encrypted PDF file.

Screenshot of opening a password-encrypted PDF file
Opening a password-encrypted PDF file
Upload your file (Drag file here)
using System;
using GemBox.Pdf;
using GemBox.Pdf.Security;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        try
        {
            // Load PDF document from a potentially encrypted PDF file.
            using (var document = PdfDocument.Load("%InputFileName%", 
                new PdfLoadOptions() { Password = "%DocumentOpenPassword%" }))
            {
                // Remove encryption from an output PDF file.
                document.SaveOptions.Encryption = null;

                // Save PDF document to an unencrypted PDF file.
                document.Save("Decryption.pdf");
            }
        }
        catch (InvalidPdfPasswordException ex)
        {
            // Gracefully handle the case when input PDF file is encrypted 
            // and provided password is invalid.
            Console.WriteLine(ex.Message);
        }
    }
}
Imports System
Imports GemBox.Pdf
Imports GemBox.Pdf.Security

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Try

            ' Load PDF document from a potentially encrypted PDF file.
            Using document = PdfDocument.Load("%InputFileName%",
                New PdfLoadOptions() With {.Password = "%DocumentOpenPassword%"})

                ' Remove encryption from an output PDF file.
                document.SaveOptions.Encryption = Nothing

                'Save PDF document to an unencrypted PDF file.
                document.Save("Decryption.pdf")
            End Using

        Catch ex As InvalidPdfPasswordException

            ' Gracefully handle the case when input PDF file is encrypted
            ' and provided password is invalid.
            Console.WriteLine(ex.Message)
        End Try
    End Sub
End Module

To decrypt a PDF file when loading a PDF document, either the Document Open or the Permissions password must be specified in the PdfLoadOptions.Password property.

If the specified password is invalid, then an InvalidPdfPasswordException is thrown.

If the input PDF file is not encrypted or is encrypted but with an empty Document Open password (like in the Restrict Editing example), then the password specified in the PdfLoadOptions.Password property is not used.

Note that GemBox.Pdf verifies the password only when the first string or stream from an encrypted PDF file has to be read, since only strings and streams are subject to encryption, based on the PDF specification.
As a consequence, an InvalidPdfPasswordException might be thrown after the loading of a PDF document.
This behavior enables you to extract some useful information from an encrypted PDF file without knowing its Document Open password, like number of pages or other information that doesn't directly reference any string or stream.

Restrict editing of a PDF file

The following example shows how to restrict editing of an existing PDF file.

Screenshot of PDF file with editing restrictions set with GemBox.Pdf
PDF file with editing restrictions set with GemBox.Pdf
Upload your file (Drag file here)
using GemBox.Pdf;
using GemBox.Pdf.Security;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Load PDF document from an unencrypted PDF file.
        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Set password-based encryption to an output PDF file.
            var encryption = document.SaveOptions.SetPasswordEncryption();

            // Specify password required to edit a PDF document.
            encryption.PermissionsPassword = "%PermissionsPassword%";

            // User will be able to print PDF and fill-in PDF form 
            // without requiring a password.
            encryption.Permissions = 
                PdfUserAccessPermissions.Print | 
                PdfUserAccessPermissions.FillForm | 
                PdfUserAccessPermissions.CopyContentForAccessibility | 
                PdfUserAccessPermissions.PrintHighResolution;

            // Save PDF document to an encrypted PDF file.
            document.Save("Restrict Editing.pdf");
        }
    }
}
Imports GemBox.Pdf
Imports GemBox.Pdf.Security

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        ' Load PDF document from an unencrypted PDF file.
        Using document = PdfDocument.Load("%InputFileName%")

            ' Set password-based encryption to an output PDF file.
            Dim encryption = document.SaveOptions.SetPasswordEncryption()

            ' Specify password required to edit a PDF document.
            encryption.PermissionsPassword = "%PermissionsPassword%"

            ' User will be able to print PDF and fill-in PDF form
            ' without requiring a password.
            encryption.Permissions =
                PdfUserAccessPermissions.Print Or
                PdfUserAccessPermissions.FillForm Or
                PdfUserAccessPermissions.CopyContentForAccessibility Or
                PdfUserAccessPermissions.PrintHighResolution

            ' Save PDF document to an encrypted PDF file.
            document.Save("Restrict Editing.pdf")
        End Using
    End Sub
End Module

PDF encryption enables enforcement of various user access permissions. In the above example, users are permitted to print a document only and fill in an interactive form if it exists in the document. Applications are permitted to copy text and graphics for accessibility (for example, to users with disabilities).

Note that enforcement of user access permissions is done by the PDF viewer/editor application in which the PDF file is opened and can be bypassed by applications that do not respect PDF specification requirements.

GemBox.Pdf does not respect PDF specification requirements regarding user access permissions because it is not an end-user application.

Also note that although a PDF file is encrypted, a password is not required to open it.

Specify encryption settings

The following example shows how to encrypt an existing PDF file using various encryption settings.

Screenshot of PDF file with encryption settings set with GemBox.Pdf
PDF file with encryption settings set with GemBox.Pdf
Upload your file (Drag file here)
using GemBox.Pdf;
using GemBox.Pdf.Security;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Load PDF document from an unencrypted PDF file.
        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Set password-based encryption to an output PDF file.
            var encryption = document.SaveOptions.SetPasswordEncryption();

            // Specify password required to open a PDF document.
            encryption.DocumentOpenPassword = "%DocumentOpenPassword%";

            // Specify password required to edit a PDF document.
            encryption.PermissionsPassword = "%PermissionsPassword%";

            // User will be able to print PDF and fill-in PDF form 
            // without requiring a password.
            encryption.Permissions =
                PdfUserAccessPermissions.Print |
                PdfUserAccessPermissions.FillForm |
                PdfUserAccessPermissions.CopyContentForAccessibility |
                PdfUserAccessPermissions.PrintHighResolution;

            // Specify 256-bit AES encryption level (supported in Acrobat X and later).
            encryption.EncryptionLevel = new PdfEncryptionLevel(PdfEncryptionAlgorithm.AES, 256);

            // Encrypt content and embedded files but do not encrypt document's metadata.
            encryption.Options = PdfEncryptionOptions.EncryptContent | PdfEncryptionOptions.EncryptEmbeddedFiles;

            // Save PDF document to an encrypted PDF file.
            document.Save("Encryption Settings.pdf");
        }
    }
}
Imports GemBox.Pdf
Imports GemBox.Pdf.Security

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        ' Load PDF document from an unencrypted PDF file.
        Using document = PdfDocument.Load("%InputFileName%")

            ' Set password-based encryption to an output PDF file.
            Dim encryption = document.SaveOptions.SetPasswordEncryption()

            ' Specify password required to open a PDF document.
            encryption.DocumentOpenPassword = "%DocumentOpenPassword%"

            ' Specify password required to edit a PDF document.
            encryption.PermissionsPassword = "%PermissionsPassword%"

            ' User will be able to print PDF and fill-in PDF form
            ' without requiring a password.
            encryption.Permissions =
                PdfUserAccessPermissions.Print Or
                PdfUserAccessPermissions.FillForm Or
                PdfUserAccessPermissions.CopyContentForAccessibility Or
                PdfUserAccessPermissions.PrintHighResolution

            ' Specify 256-bit AES encryption level (supported in Acrobat X and later).
            encryption.EncryptionLevel = New PdfEncryptionLevel(PdfEncryptionAlgorithm.AES, 256)

            ' Encrypt content and embedded files but do not encrypt document's metadata.
            encryption.Options = PdfEncryptionOptions.EncryptContent Or PdfEncryptionOptions.EncryptEmbeddedFiles

            ' Save PDF document to an encrypted PDF file.
            document.Save("Encryption Settings.pdf")
        End Using
    End Sub
End Module

The first part of this example is a combination of Encrypt and Restrict Editing examples so a password (either Document Open or Permissions) will be required to open a document and only users who entered a Permissions password will be able to edit a document in a PDF editor application.

The last part of this example shows how to set the encryption to the strongest level currently supported by PDF password-based encryption – 256-bit AES supported by Adobe Acrobat X and later.
It also shows how to specify which parts of a PDF file should be encrypted. In this example, the document's metadata stream is excluded from encryption so search engines will be able to access it.

Check next example or download examples from GitHub.