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 CoreE-Invoicing

Why Structured E-Invoices Still Need Tamper Protection using C# and .NET

ZUGFeRD, Factur-X, German e-invoicing rules, and how to seal PDF invoices with TX Text Control to prevent tampering. Learn how to create compliant e-invoices with C# and .NET.


ASP.NETASP.NET CoreForms

Create Fillable PDFs from HTML Forms in C# ASP.NET Core Using a WYSIWYG Template

Learn how to generate PDFs from HTML forms in ASP.NET Core using a pixel-perfect WYSIWYG template. Extract form fields from a document, render a dynamic HTML form, and merge the data server-side…


ASP.NETASP.NET CoreHTML

Why HTML to PDF Conversion is Often the Wrong Choice for Business Documents…

In this article, we explore the challenges of HTML to PDF conversion for business documents in C# .NET and present alternative solutions that offer better performance and reliability. Discover why…


ASP.NETASP.NET CoreMarkdown

A Complete Guide to Converting Markdown to PDF in .NET C#

Learn how to convert Markdown to PDF in .NET C# using Text Control's ServerTextControl component. This guide covers setup, conversion process, and customization options for generating high-quality…

Share on this blog post on: