Products Technologies Demo Docs Blog Support Company

How to Verify PDF Encryption Programmatically in C# .NET

This article explains how to programmatically verify the encryption of a PDF document using C# .NET. It provides the necessary steps and code examples to ensure the PDF is encrypted correctly, offering a secure method for handling sensitive documents within your applications.

How to Verify PDF Encryption Programmatically in C# .NET

PDF encryption is a key requirement in many applications where sensitive documents need protection from unauthorized access. With TX Text Control, you can encrypt PDF documents with a user-defined password and programmatically verify that the encryption is working properly, all within a few lines of C# code.

This article will show you how to create an encrypted PDF document and verify the encryption by attempting to open the file under different conditions.

Saving an Encrypted PDF

TX Text Control offers several encryption options for saving PDF documents. With the SaveSettings.UserPassword property, you can set a password that is required to open the document. Below is a short example that saves a PDF document with password protection:

using var serverTextControl = new ServerTextControl();
serverTextControl.Create();
serverTextControl.Text = "This is a sample document.";

var saveSettings = new SaveSettings {
    UserPassword = "user1234"
};

serverTextControl.Save("EncryptedDocument.pdf", StreamType.AdobePDF, saveSettings);

How do you verify that the encryption actually worked? Sure, you can open the PDF in Acrobat Reader. When prompted for a password, the document will be successfully signed. However, we want to ensure that the process has been completed successfully programmatically.

Verifying the Encryption

To ensure the PDF is properly encrypted, attempt to load it without a password. If it fails, the file is encrypted. If it fails with error code 1-1D10, then we know the file is encrypted. Then, we can retry loading the file with the correct password to see if it succeeds. We've wrapped this process into a reusable method.

using TXTextControl;

public static class PdfEncryptionHelper
{
    public static bool SaveAndVerifyPdfEncryption(ServerTextControl sourceTextControl, string userPassword, string destinationPath)
    {
        // Save the document encrypted
        var saveSettings = new SaveSettings
        {
            UserPassword = userPassword
        };

        try
        {
            sourceTextControl.Save(destinationPath, StreamType.AdobePDF, saveSettings);
            Console.WriteLine($"PDF saved with encryption at: {destinationPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed to save PDF: {ex.Message}");
            return false;
        }

        // Try to load the PDF without a password (should fail)
        using var verificationControl = new ServerTextControl();
        verificationControl.Create();

        try
        {
            verificationControl.Load(destinationPath, StreamType.AdobePDF);
            Console.WriteLine("Unexpected: PDF loaded without a password.");
            return false; // Not encrypted properly
        }
        catch (FilterException exc)
        {
            if (!exc.Message.Contains("1-1D10"))
            {
                Console.WriteLine($"Unexpected error when loading PDF: {exc.Message}");
                return false;
            }

            // Expected: encryption detected, now try with password
            try
            {
                var loadSettings = new LoadSettings
                {
                    UserPassword = userPassword
                };

                verificationControl.Load(destinationPath, StreamType.AdobePDF, loadSettings);
                Console.WriteLine("PDF decrypted and loaded successfully.");
                return true;
            }
            catch (FilterException loadExc)
            {
                Console.WriteLine($"Decryption failed: {loadExc.Message}");
                return false;
            }
        }
    }
}

Usage

To use the above method, simply call it with the path to your PDF file and the password you set when saving the document. If the method returns true, the encryption is verified successfully.

using var serverTextControl = new ServerTextControl();
serverTextControl.Create();
serverTextControl.Text = "This is a sample document.";

bool success = SaveAndVerifyPdfEncryption(serverTextControl, "user1234", "EncryptedDocument.pdf");

Console.WriteLine($"Encryption verification result: {success}");

Conclusion

TX Text Control simplifies the process of encrypting PDF documents and verifying that the encryption is functioning properly. Using the provided methods ensures that your sensitive documents are protected against unauthorized access.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreEncryption

PDF Security for C# Developers: Encryption and Permissions in .NET

In this article, we will explore how to implement PDF security in .NET applications using TX Text Control. We discuss encryption methods and permission settings that protect sensitive information…


ASP.NETASP.NET CoreMarkdown

Convert Markdown to PDF in a Console Application on Linux and Windows

Learn how to convert Markdown files to PDF in a console application on Linux and Windows using TX Text Control .NET Server for ASP.NET. This tutorial provides step-by-step instructions and code…


ASP.NETASP.NET CoreExtraction

Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas

Mining PDFs with Regex in C# can be a powerful technique for extracting information from documents. This article explores practical patterns, tips, and ideas for effectively using regular…


ASP.NETASP.NET CoreForms

Streamline Data Collection with Embedded Forms in C# .NET

Discover how to enhance your C# .NET applications by embedding forms for data collection. This article explores the benefits of using Text Control's ASP.NET and ASP.NET Core components to create…


ASP.NETASP.NET CorePDF

Adding QR Codes to PDF Documents in C# .NET

This article explains how to add QR codes to PDF documents with the Text Control .NET Server component in C#. It provides the necessary steps and code snippets for effectively implementing this…