> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/xamarin/get-started/samples/enctest.md).

# Encryption

Learn how to encrypt and decrypt PDF files in Apryse SDK.  It includes samples to encrypt and decrypt PDFs using C#

Sample C# code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our [Xamarin SDK](/core/get-started/frameworks/dotnet.md).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
//

using System;
using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

using NUnit.Framework;

namespace MiscellaneousSamples
{
	// A custom security handler used to obtain document password dynamically via user feedback. 
	/// <summary>
	//---------------------------------------------------------------------------------------
	// This sample shows encryption support in PDFNet. The sample reads an encrypted document and 
	// sets a new SecurityHandler. The sample also illustrates how password protection can 
	// be removed from an existing PDF document.
	//---------------------------------------------------------------------------------------
	/// </summary>
	[TestFixture]
	public class EncTest
	{
		
		[Test]
		public static void Sample()
		{

			// Relative path to the folder containing test files.
			const string input_path =  "TestFiles/";

			// Example 1: Securing a document with password protection and adjusting permissions 
			// on the document.
			try
			{
				// Open the test file
				Console.WriteLine("-------------------------------------------------");
				Console.WriteLine("Securing an existing document...");
				using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "fish.pdf")))
				{

					if (!doc.InitSecurityHandler()) 
					{
						Console.WriteLine("Document authentication error...");
						return;
					}
					
					// Perform some operation on the document. In this case we use low level SDF API
					// to replace the content stream of the first page with contents of file 'my_stream.txt'
					if (true)  // Optional
					{
						Console.WriteLine("Replacing the content stream, use flate compression...");

						// Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0
						Obj page_dict = doc.GetTrailer().Get("Root").Value().
							Get("Pages").Value().Get("Kids").Value().GetAt(0);

						// Embed a custom stream (file mystream.txt) using Flate compression.
						MappedFile embed_file = new MappedFile(Utils.GetAssetTempFile(input_path + "my_stream.txt"));
						FilterReader mystm = new FilterReader(embed_file);
						page_dict.Put("Contents", doc.CreateIndirectStream(mystm));
						embed_file.Close();
					}
				
					// Apply a new security handler with given security settings. 
					// In order to open saved PDF you will need a user password 'test'.
					SecurityHandler new_handler = new SecurityHandler();
					// Set a new password required to open a document
					string my_password = "test";				
					new_handler.ChangeUserPassword(my_password);

					// Set Permissions
					new_handler.SetPermission (SecurityHandler.Permission.e_print, true);
					new_handler.SetPermission (SecurityHandler.Permission.e_extract_content, false);

					// Note: document takes the ownership of new_handler.
					doc.SetSecurityHandler(new_handler);

					// Save the changes.
					Console.WriteLine("Saving modified file...");
					doc.Save(Utils.CreateExternalFile("secured.pdf"), 0);
				}

				Console.WriteLine("Done. Result saved in secured.pdf");
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
				Assert.True(false);
			}

			// Example 2: Reading password protected document without user feedback.
			try
			{
				// In this sample case we will open an encrypted document that 
				// requires a user password in order to access the content.
				Console.WriteLine("-------------------------------------------------");
				Console.WriteLine("Open the password protected document from the first example...");
				using (PDFDoc doc = new PDFDoc(Utils.CreateExternalFile("secured.pdf")))	// Open the encrypted document that we saved in the first example. 
				{

					Console.WriteLine("Initializing security handler without any user interaction...");
					
					// At this point MySecurityHandler callbacks will be invoked. 
					// MySecurityHandler.GetAuthorizationData() should collect the password and 
					// AuthorizeFailed() is called if user repeatedly enters a wrong password.
					if (!doc.InitStdSecurityHandler("test")) 
					{
						Console.WriteLine("Document authentication error...");
						Console.WriteLine("The password is not valid.");
						return;
					}
					else 
					{
						Console.WriteLine("The password is correct! Document can now be used for reading and editing");

						// Remove the password security and save the changes to a new file.
                        doc.RemoveSecurity();
						doc.Save(Utils.CreateExternalFile("secured_nomore1.pdf"), 0);
						Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
					}

				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
				Assert.True(false);
			}
			
			Console.WriteLine("Tests completed.");

		}
	}
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.apryse.com/xamarin/get-started/samples/enctest.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
