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 CoreDocument Conversion

Convert DOCX to PDF, PDF/A and PDF/UA in C# Using TX Text Control

Learn how to convert Word DOCX documents to PDF in C# using TX Text Control .NET Server. This tutorial covers file-based and in-memory conversion, PDF/A export, document metadata, font deployment,…


ASP.NETASP.NET CoreMCP

Reliable Document AI in .NET: LLM Tool Calling vs. LLM-Generated Files

Reliable document AI needs a deterministic engine. With LLM tool calling, the LLM decides what the document should contain, and TX Text Control generates the file.


ASP.NETASP.NET CoreDocument Generation

Building a Production-Ready PDF Generation Pipeline in C# with ASP.NET Core

Learn how to build a reliable PDF generation pipeline with TX Text Control and ASP.NET Core. Use durable background jobs, idempotency, renewable leases, PDF validation, and private artifact…


ASP.NETASP.NET CoreDocument Viewer

Native PDF Annotation Support Is Coming to the TX Text Control Document Viewer

The next version of the TX Text Control Document Viewer will introduce an important enhancement to PDF workflows: native support for PDF-compatible annotations. Users will be able to add…

Share this blog post on:

​​​