Encryption in PDF file using C# and .NET

In the modern world of information security, protecting confidential documents is becoming an essential task for developers and companies. One of the popular ways to protect digital documents, such as PDF files, is encryption. In this article, we will explain in detail how to implement PDF file encryption using C# and .NET, using the powerful SautinSoft PDF .Net library. We will also discuss the advantages of this approach, its practical application, and the specifics of its use.

PDF encryption provides many advantages:

  • Protection of confidential information: encryption prevents unauthorized access to the contents of the document.
  • Integrity assurance: in addition to protecting the content, encryption helps ensure that the document has not been modified.
  • Compliance with regulations: for many sectors (finance, medicine, law), document encryption is a mandatory requirement.
  • Access control: you can set restrictions on printing, copying text, or editing.

In light of these advantages, PDF encryption is becoming an integral part of enterprise document management solutions.

Statistics show that:

  • In the corporate environment, the level of document protection is constantly increasing.
  • In the financial sector, more than 80% of electronic documents are password protected.
  • Encryption is a standard practice in law firms and government agencies.
  • In e-commerce and logistics, similar methods are used to protect contracts and reports.
This suggests that PDF encryption is not a temporary trend, but a key component of secure information exchange.
We suggest you review the sample code step-by-step:

  1. We'll work with PDF documents.
  2. Dependencies: SautinSoft.PDF.
  3. Example №1: Load pdf and set a password.
  4. Example №2: Load pdf, set a password and User will be able to print PDF and fill in the PDF form without requiring a password.
  5. Example №3: Load pdf and set a User password and a Owner password.
  6. Example №4: Load pdf and remove all passwords inside.
  7. Example №5: Load pdf and ask about password: Correct/incorrect

Complete code

using System;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Security;

class Program
{
    /// <summary>
    /// Encryption.
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/Encryption.php
    /// </remarks>
    static void Main()
    {
        Example1();
        Example2();
        Example3();
        Example4();
        Example5();
    }

    static void Example1()
    {
       

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

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

    static void Example2()
    {
       

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

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

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

            // Save the PDF document to an encrypted PDF file.
            document.Save("Restrict Editing.pdf");
        }
    }

    static void Example3()
    {
      

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

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

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

            // 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");
        }
    }

    static void Example4()
    {

        try
        {
            // Load PDF document from a potentially encrypted PDF file.
            using (var document = PdfDocument.Load("Encryption.pdf",
                new PdfLoadOptions() { Password = "useruser" }))
            {
                // 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);
        }
    }

    static void Example5()
    {


        var loadOptions = new PdfLoadOptions();
        loadOptions.AuthorizationOnDocumentOpen = true;

        loadOptions.LoadingEncrypted += (sender, e) =>
        {
            Console.WriteLine("PDF file is encrypted, please enter the password:");
            bool wrongPassword;

            do
            {
                string password = Console.ReadLine();
                if (string.IsNullOrEmpty(password))
                    break;

                wrongPassword = !e.SetPassword(password);
                if (wrongPassword)
                    Console.WriteLine("The password is incorrect, please try again:");
            }
            while (wrongPassword);
        };

        try
        {
            using (var document = PdfDocument.Load("Encryption.pdf", loadOptions))
            {
                Console.WriteLine("The correct password was provided.");
            }
        }
        catch (InvalidPdfPasswordException)
        {
            Console.WriteLine("The incorrect password was provided.");
        }
    }
}

Download

Option Infer On

Imports System
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Security

Friend Class Program
	''' <summary>
	''' Encryption.
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/Encryption.php
	''' </remarks>
	Shared Sub Main()
		Example1()
		Example2()
		Example3()
		Example4()
		Example5()
	End Sub

	Private Shared Sub Example1()


		' Load PDF document from an unencrypted PDF file.
		Using document = PdfDocument.Load("Reading.pdf")
			' Set password-based encryption with password required to open a PDF document.
			document.SaveOptions.SetPasswordEncryption().DocumentOpenPassword = "useruser"

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

	Private Shared Sub Example2()


		' Load PDF document from an unencrypted PDF file.
		Using document = PdfDocument.Load("Reading.pdf")
			' Set password-based encryption to an output PDF file.
			Dim encryption = document.SaveOptions.SetPasswordEncryption()

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

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

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

	Private Shared Sub Example3()


		' Load PDF document from an unencrypted PDF file.
		Using document = PdfDocument.Load("Reading.pdf")
			' Set password-based encryption to an output PDF file.
			Dim encryption = document.SaveOptions.SetPasswordEncryption()

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

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

			' 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

	Private Shared Sub Example4()

		Try
			' Load PDF document from a potentially encrypted PDF file.
			Using document = PdfDocument.Load("Encryption.pdf", New PdfLoadOptions() With {.Password = "useruser"})
				' 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

	Private Shared Sub Example5()


		Dim loadOptions = New PdfLoadOptions()
		loadOptions.AuthorizationOnDocumentOpen = True

		AddHandler loadOptions.LoadingEncrypted, Sub(sender, e)
			Console.WriteLine("PDF file is encrypted, please enter the password:")
			Dim wrongPassword As Boolean

			Do
				Dim password As String = Console.ReadLine()
				If String.IsNullOrEmpty(password) Then
					Exit Do
				End If

				wrongPassword = Not e.SetPassword(password)
				If wrongPassword Then
					Console.WriteLine("The password is incorrect, please try again:")
				End If
			Loop While wrongPassword
		End Sub

		Try
			Using document = PdfDocument.Load("Encryption.pdf", loadOptions)
				Console.WriteLine("The correct password was provided.")
			End Using
		Catch e1 As InvalidPdfPasswordException
			Console.WriteLine("The incorrect password was provided.")
		End Try
	End Sub
End Class

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:


Captcha

Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.