How to Encrypt and Password-Protect a PDF using C# .NET Framework

Cloudmersive
2 min readJan 21, 2024

--

Coding workflows to secure our PDF documents can be a time-consuming challenge. Thankfully, with a free low-code solution, we can avoid the bulk of that work and come up with consistent, reliable results.

Using the ready-to-run C# code further down the page, we can easily take advantage of a free API to encrypt and password-protect our PDF documents. We can set user & owner passwords with simple request parameters, and we can even choose from two distinct encryption key lengths (options are 128-bit RC4 encryption & 256-bit AES encryption; the latter is default).

We can start structuring our API call by installing the SDK. We can run the following command in our Package Manager console to install via NuGet:

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2

Next, before we call our function, let’s grab a free-tier API key to authorize our API calls. This will allow a limit of 800 API calls per month with no additional commitments.

Now let’s copy the below code and customize our request:

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;

namespace Example
{
public class EditPdfEncryptExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");

var apiInstance = new EditPdfApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.
var userPassword = userPassword_example; // string | Password of a user (reader) of the PDF file (optional)
var ownerPassword = ownerPassword_example; // string | Password of a owner (creator/editor) of the PDF file (optional)
var encryptionKeyLength = encryptionKeyLength_example; // string | Possible values are \"128\" (128-bit RC4 encryption) and \"256\" (256-bit AES encryption). Default is 256. (optional)

try
{
// Encrypt and password-protect a PDF
byte[] result = apiInstance.EditPdfEncrypt(inputFile, userPassword, ownerPassword, encryptionKeyLength);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling EditPdfApi.EditPdfEncrypt: " + e.Message );
}
}
}
}

Just like that, we now have free low-code solution to streamline our PDF security workflows.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet