> 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/core/get-started/samples/enctest.md).

# Encrypt & Decrypt PDFs - Encryption

Learn how to encrypt and decrypt PDF files in Apryse SDK.  It includes samples to encrypt and decrypt PDFs, provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/core/get-started/get-started.md" class="button primary">Server SDK</a><a href="https://apryse.com/capabilities#Security" class="button primary">Package: Security</a><a href="https://showcase.apryse.com/password-protect" class="button primary">Live demo</a>
{% endhint %}

Sample code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our [Server SDK](/core/get-started/get-started.md).

### **Implementation steps**

To encrypt and decrypt files with Apryse Server SDK:

Step 1: Follow [get started with Server SDK in your preferred language or framework](/core/get-started/get-started.md) Step 2: Add the sample code provided in this guide

To use this feature in production, your license key will need the [Security Package](https://apryse.com/capabilities#Security). Trial keys already include all packages.

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

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

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

namespace EncTestCS
{
	// A custom security handler used to obtain document password dynamically via user feedback. 
	class MySecurityHandler : StdSecurityHandler
	{
		public MySecurityHandler (Int32 key_len, Int32 enc_code) : base(key_len, enc_code) {}
		public MySecurityHandler (MySecurityHandler s) : base(s) {}

		// In this callback ask the user for password/authorization data. 
		// This may involve a dialog box used to collect authorization data or something else.
		override public bool GetAuthorizationData (SecurityHandler.Permission p) 
		{ 
			Console.WriteLine("The input file requires user password.");
			Console.WriteLine("Please enter the password:");
			String pass = Console.ReadLine();
			InitPassword(pass);
			return true; 
		}

		// This callback could be used to customize security handler preferences.
		override public bool EditSecurityData(SDFDoc doc) { return false; }

		// This callback is used when authorization process fails. 
		override public void AuthorizeFailed() 
		{
			Console.WriteLine("Authorize failed...");
		}

		public static SecurityHandler Create(String name, Int32 key_len, Int32 enc_code) { return new MySecurityHandler(key_len, enc_code); }

		override public SecurityHandler Clone() { return new MySecurityHandler(this); }
	}

	/// <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>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

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

			// 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(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(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'.
					StdSecurityHandler new_handler = new StdSecurityHandler();

					// 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(output_path + "secured.pdf", 0);
				}

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

			// 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(output_path + "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(output_path + "secured_nomore1.pdf", 0);
						Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
					}

				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}

			// Example 3:
			// Encrypt/Decrypt a PDF using PDFTron custom security handler
			try
			{
				Console.WriteLine("-------------------------------------------------");
				Console.WriteLine("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
				PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf");

				// Create PDFTron custom security handler with a custom id. Replace this with your own integer
				int custom_id = 123456789;
				PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);

				// Add a password to the custom security handler
				String pass = "test";
				custom_handler.ChangeUserPassword(pass);

				// Save the encrypted document
				doc.SetSecurityHandler(custom_handler);
				doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0);

				Console.WriteLine("Decrypt the PDFTron custom security encrypted document above...");
				// Register the PDFTron Custom Security handler with the same custom id used in encryption
				PDFNet.AddPDFTronCustomHandler(custom_id);

				PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
				doc_enc.InitStdSecurityHandler(pass);
				doc_enc.RemoveSecurity();
				// Save the decrypted document
				doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0);
				Console.WriteLine("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}

			// Example 4: Reading password protected document with user feedback.
			try
			{
				// Register standard security. Reguired only once per application session.
				CreateDelegate del = new CreateDelegate(MySecurityHandler.Create);
				SecurityManagerSingleton.Instance().RegisterSecurityHandler("Standard", 
					new SecurityDescriptor("Standard Security", del));

				Console.WriteLine("-------------------------------------------------");
				Console.WriteLine("Open the password protected document from the first example...");
				using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example. 
				{

					Console.WriteLine("Initializing security handler. The password will now be collected from the user");
					Console.WriteLine("Enter 'test' as the password.");

					// 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.InitSecurityHandler()) 
					{
						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(output_path + "secured_nomore2.pdf", 0);
						Console.WriteLine("Done. Result saved in secured_nomore2.pdf");
					}
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
			Console.WriteLine("-------------------------------------------------");
			Console.WriteLine("Tests completed.");

		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
	"fmt"
	"strconv"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

//---------------------------------------------------------------------------------------
// 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.
//---------------------------------------------------------------------------------------

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    outputPath := "../../TestFiles/Output/"
    
    // Example 1: 
    // secure a PDF document with password protection and adjust permissions
    
    // Open the test file
    fmt.Println("Securing an existing document...")
    
    doc := NewPDFDoc(inputPath + "fish.pdf")
    doc.InitSecurityHandler()
    
    // 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
        fmt.Println("Replacing the content stream, use Flate compression...")
        
        // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
        pageDict := (doc.GetTrailer().Get("Root").Value().Get("Pages").Value().Get("Kids").Value().GetAt(0))
        
        // Embed a custom stream (file mystream.txt) using Flate compression.
        embedFile := NewMappedFile(inputPath + "my_stream.txt")
        mystm := NewFilterReader(embedFile)
        pageDict.Put("Contents", doc.CreateIndirectStream(mystm, NewFilter()))
    }   
    // encrypt the document
    
    // Apply a new security handler with given security settings.
    // In order to open saved PDF you will need a user password 'test'.
    newHandler := NewSecurityHandler()
    
    // Set a new password required to open a document
    userPassword := "test"
    newHandler.ChangeUserPassword(userPassword)
    
    // Set permissions
    newHandler.SetPermission(SecurityHandlerE_print, true)
    newHandler.SetPermission(SecurityHandlerE_extract_content, false)
    
    // Note: document takes the ownership of newHandler.
    doc.SetSecurityHandler(newHandler)
    
    // save the changes.
    fmt.Println("Saving modified file...")
    doc.Save(outputPath + "secured.pdf", uint(0))
    doc.Close()
    
    // Example 2:
    // Opens an encrypted PDF document and removes its security.
    
    doc = NewPDFDoc(outputPath + "secured.pdf")
    
    // If the document is encrypted prompt for the password
    if !doc.InitSecurityHandler(){
        success := false
        fmt.Println("The password is: test")
        count := 0
        for count < 3{
            fmt.Println("A password required to open the document.")
            var password string
            fmt.Print("Please enter the password: \n")
            fmt.Scanf("%s", &password)
            fmt.Println(password)
                
            if doc.InitStdSecurityHandler(password, len(password)){
                success = true
                fmt.Println("The password is correct.")
                break
            }else if count < 3{
                fmt.Println("The password is incorrect, please try again")
            }
            count = count + 1
        }    
        if !success{
            fmt.Println("Document authentication error....")
            return
        }
        hdlr := doc.GetSecurityHandler()
        fmt.Println("Document Open Password: " + strconv.FormatBool(hdlr.IsUserPasswordRequired()))
        fmt.Println("Permissions Password: " + strconv.FormatBool(hdlr.IsMasterPasswordRequired()))
        fmt.Println(("Permissions: " + 
                "\n\tHas 'owner' permissions: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_owner)) + 
                "\n\tOpen and decrypt the document: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_open)) +
                "\n\tAllow content extraction: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_extract_content)) +
                "\n\tAllow full document editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_modify) ) +
                "\n\tAllow printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print)) + 
                "\n\tAllow high resolution printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print_high)) + 
                "\n\tAllow annotation editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_mod_annot)) + 
                "\n\tAllow form fill: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_fill_forms)) + 
                "\n\tAllow content extraction for accessibility: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_access_support)) + 
                "\n\tAllow document assembly: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_assemble_doc))))
    }
    
    // remove all security on the document
    doc.RemoveSecurity()
    doc.Save(outputPath + "not_secured.pdf", uint(0))
    doc.Close()
    
    PDFNetTerminate()
    fmt.Println("Test completed.")
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.pdftron.common.PDFNetException;
import com.pdftron.filters.FilterReader;
import com.pdftron.filters.FlateEncode;
import com.pdftron.filters.MappedFile;
import com.pdftron.pdf.*;
import com.pdftron.sdf.*;


//---------------------------------------------------------------------------------------
// 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.
//---------------------------------------------------------------------------------------
public class EncTest {
    public static void main(String[] args) {
        PDFNet.initialize(PDFTronLicense.Key());

        // Relative path to the folder containing test files.
        String input_path = "../../TestFiles/";
        String output_path = "../../TestFiles/Output/";

        // Example 1:
        // secure a document with password protection and
        // adjust permissions

        // Open the test file
        System.out.println("Securing an existing document ...");
        try (PDFDoc doc = new PDFDoc((input_path + "fish.pdf"))) {
            doc.initSecurityHandler();

            // 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
            {
                System.out.println("Replacing the content stream, use flate compression...");

                // Get the 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((input_path + "my_stream.txt"));
                FilterReader mystm = new FilterReader(embed_file);
                page_dict.put("Contents",
                        doc.createIndirectStream(mystm,
                                new FlateEncode(null)));
            }

            //encrypt the document

            // 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 user_password = "test";
            new_handler.changeUserPassword(user_password);

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

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

            // Save the changes.
            System.out.println("Saving modified file...");
            doc.save((output_path + "secured.pdf"), SDFDoc.SaveMode.NO_FLAGS, null);
        } catch (PDFNetException e) {
            e.printStackTrace();
        }

        // Example 2:
        // Opens the encrypted document and removes all of
        // its security.
        try (PDFDoc doc = new PDFDoc((output_path + "secured.pdf"))) {
            //If the document is encrypted prompt for the password
            if (!doc.initSecurityHandler()) {
                boolean success = false;
                System.out.println("The password is: test");
                for (int count = 0; count < 3; count++) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                    System.out.println("A password required to open the document.");
                    System.out.print("Please enter the password: ");
                    String password = r.readLine();
                    if (doc.initStdSecurityHandler(password)) {
                        success = true;
                        System.out.println("The password is correct.");
                        break;
                    } else if (count < 3) {
                        System.out.println("The password is incorrect, please try again");
                    }
                }
                if (!success) {
                    System.out.println("Document authentication error....");
                    PDFNet.terminate();
                }
            }

            //remove all security on the document
            doc.removeSecurity();
            doc.save(output_path + "not_secured.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Example 3:
        // Encrypt/Decrypt a PDF using PDFTron custom security handler
        System.out.println("-------------------------------------------------");
        System.out.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
        try (PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf"))
        {   
            // Create PDFTron custom security handler with a custom id. Replace this with your own integer
            int custom_id = 123456789;
            PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);

            // Add a password to the custom security handler
            String pass = "test";
            custom_handler.changeUserPassword(pass);

            // Save the encrypted document
            doc.setSecurityHandler(custom_handler);
            doc.save(output_path + "BusinessCardTemplate_enc.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
                    
            System.out.println("Decrypt the PDFTron custom security encrypted document above...");
            // Register the PDFTron Custom Security handler with the same custom id used in encryption
            PDFNet.addPDFTronCustomHandler(custom_id);

            PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
            doc_enc.initStdSecurityHandler(pass);
            doc_enc.removeSecurity();
            // Save the decrypted document
            doc_enc.save(output_path + "BusinessCardTemplate_enc_dec.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
            System.out.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("-------------------------------------------------");
        System.out.println("Tests completed.");
        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <SDF/SecurityHandler.h>
#include <SDF/PDFTronCustomSecurityHandler.h>
#include <Filters/FilterReader.h>
#include <Filters/FlateEncode.h>
#include <Filters/MappedFile.h>
#include <iostream>
#include <string>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace std;

using namespace pdftron;
using namespace SDF;
using namespace PDF;
using namespace Filters;


//---------------------------------------------------------------------------------------
// 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.
//---------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
	int ret = 0;
	PDFNet::Initialize(LicenseKey);

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

	// Example 1: 
	// secure a PDF document with password protection and adjust permissions 
	
	try
	{
		// Open the test file
		cout << "-------------------------------------------------" << endl << "Securing an existing document..." << endl;
		PDFDoc doc((input_path + "fish.pdf").c_str());
		if (!doc.InitSecurityHandler())
		{
			cout << "Document authentication error..." << endl;
			ret = 1;
		}
		
		
		// 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
		{
			cout << "Replacing the content stream, use flate compression..." << endl;

			// Get the 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((input_path + "my_stream.txt"));
			FilterReader mystm(embed_file);
			page_dict.Put("Contents", 
				doc.CreateIndirectStream(mystm,  
				FlateEncode(Filter())));
		}

		//encrypt the document


		// 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;

		// Set a new password required to open a document
		const char* user_password="test";
		new_handler.ChangeUserPassword(user_password);

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

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

		// Save the changes.
		cout << "Saving modified file..." << endl;
		doc.Save((output_path + "secured.pdf").c_str(), 0, NULL);

		cout << "Done. Result saved in secured.pdf" << endl;
	}
	catch(Common::Exception& e) {
		cout << e << endl;
		ret = 1;
	}
	catch(...) {
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	// Example 2:
	// Opens an encrypted PDF document and removes its security.

	try
	{
		cout << "-------------------------------------------------" << endl;
		cout << "Open the password protected document from the first example..." << endl;

		// Open the encrypted document that we saved in the first example. 
		PDFDoc doc((output_path + "secured.pdf").c_str());

		cout << "Initializing security handler without any user interaction..." << endl;

		// 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"))
		{
			cout << "Document authentication error..." << endl << "The password is not valid." << endl;
			ret = 1;
		}
		else
		{
			cout << "The password is correct! Document can now be used for reading and editing" << endl;

			// Remove the password security and save the changes to a new file.
			doc.RemoveSecurity();
			doc.Save(output_path + "secured_nomore1.pdf", 0, NULL);
			cout << "Done. Result saved in secured_nomore1.pdf" << endl;

			/*
			SecurityHandler hdlr = doc.GetSecurityHandler();
			cout << "Document Open Password: " << hdlr.IsUserPasswordRequired() << endl;
			cout << "Permissions Password: " << hdlr.IsMasterPasswordRequired() << endl;
			cout << "Permissions: "
				<< "\n\tHas 'owner' permissions: " << hdlr.GetPermission(SecurityHandler::e_owner)
				<< "\n\tOpen and decrypt the document: " << hdlr.GetPermission(SecurityHandler::e_doc_open)
				<< "\n\tAllow content extraction: " << hdlr.GetPermission(SecurityHandler::e_extract_content)
				<< "\n\tAllow full document editing: " << hdlr.GetPermission(SecurityHandler::e_doc_modify)
				<< "\n\tAllow printing: " << hdlr.GetPermission(SecurityHandler::e_print)
				<< "\n\tAllow high resolution printing: " << hdlr.GetPermission(SecurityHandler::e_print_high)
				<< "\n\tAllow annotation editing: " << hdlr.GetPermission(SecurityHandler::e_mod_annot)
				<< "\n\tAllow form fill: " << hdlr.GetPermission(SecurityHandler::e_fill_forms)
				<< "\n\tAllow content extraction for accessibility: " << hdlr.GetPermission(SecurityHandler::e_access_support)
				<< "\n\tAllow document assembly: " << hdlr.GetPermission(SecurityHandler::e_assemble_doc)
				<< endl;
			*/
		}
	}
	catch(Common::Exception& e) {
		cout << e << endl;
		ret = 1;
	}
	catch(...) {
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	// An advanced example showing how to work with custom security handlers. 
	// A custom security handler is a class derived from a SecurityHandler.

	// Define a custom security handler used to obtain document password dynamically via user feedback. 
	class MySecurityHandler : public SecurityHandler
	{
	public:
		MySecurityHandler (int key_len, int enc_code) : SecurityHandler("Standard", key_len, enc_code) {}
		MySecurityHandler (const MySecurityHandler& s) : SecurityHandler(s) {}
		virtual ~MySecurityHandler() {
			// cout << "MySecurityHandler Destroy";
		}

		// In this callback ask the user for password/authorization data. 
		// This may involve a dialog box used to collect authorization data or something else.
		virtual bool GetAuthorizationData (Permission p) 
		{
			cout << "The input file requires user password." << endl;
			cout << "Please enter the password:" << endl;

			string password;
			cin >> password;

			InitPassword(password.c_str());
			return true; 
		}

		// This callback could be used to customize security handler preferences.
		virtual bool EditSecurityData(SDF::SDFDoc& doc) { return false; }

		// This callback is used when authorization process fails. 
		virtual void AuthorizeFailed() { cout << "Authorize failed...." << endl; }


		MySecurityHandler(const MySecurityHandler& s, TRN_SecurityHandler base) 
			: SecurityHandler(base, true, s.m_derived_procs) 
		{
		}

		virtual SecurityHandler* Clone(TRN_SecurityHandler base) const 
		{
			return new MySecurityHandler(*this, base);
		}

		// MySecurityHandler's factory method
		static TRN_SecurityHandler Create(const char* name, int key_len, int enc_code, void* custom_data) 
		{ 
			MySecurityHandler* ret = new MySecurityHandler (key_len, enc_code);

			// Explicitly specify which methods are overloaded.
			ret->SetDerived(
				has_CloneProc |   // Clone - must be implemented in every derived class.
				has_AuthFailedProc |
				has_GetAuthDataProc);
			return (TRN_SecurityHandler) ret->mp_handler;
		}
	};

	// Example 3:
	// Encrypt/Decrypt a PDF using PDFTron custom security handler
	try
	{
		cout << "-------------------------------------------------" << endl;
		cout << "Encrypt a document using PDFTron Custom Security handler with a custom id and password..." << endl;
		PDFDoc doc(input_path + "BusinessCardTemplate.pdf");

		// Create PDFTron custom security handler with a custom id. Replace this with your own integer
		UInt32 custom_id = 123456789;
		SDF::PDFTronCustomSecurityHandler custom_handler(custom_id);

		// Add a password to the custom security handler
		const UString pass("test");
		custom_handler.ChangeUserPassword(pass);

		// Save the encrypted document
		doc.SetSecurityHandler(custom_handler);
		doc.Save((output_path + "BusinessCardTemplate_enc.pdf").c_str(), SDFDoc::e_linearized, 0);

		cout << "Decrypt the PDFTron custom security encrypted document above..." << endl;
		// Register the PDFTron Custom Security handler with the same custom id used in encryption
		PDFNet::AddPDFTronCustomHandler(custom_id);

		PDFDoc doc_enc(output_path + "BusinessCardTemplate_enc.pdf");
		doc_enc.InitStdSecurityHandler(pass);
		doc_enc.RemoveSecurity();
		// Save the decrypted document
		doc_enc.Save((output_path + "BusinessCardTemplate_enc_dec.pdf").c_str(), SDFDoc::e_linearized, 0);
		cout << "Done. Result saved in BusinessCardTemplate_enc_dec.pdf" << endl;
	}
	catch (Common::Exception & e) {
		cout << e << endl;
		ret = 1;
	}
	catch (...) {
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	// Example 4:
	// Read a password protected PDF using a custom security handler.

	try
	{
		// Register standard security. Required only once per application session.
		PDFNet::RegisterSecurityHandler("Standard", "Standard Security", MySecurityHandler::Create);

		cout << "-------------------------------------------------" << endl;
		cout << "Open the password protected document from the first example..." << endl;
		PDFDoc doc((output_path + "secured.pdf").c_str());  // Open the encrypted document that we saved in the first example. 

		cout << "Initializing security handler. The password will now be collected from the user" << endl;
		cout << "Enter 'test' as the password." << endl;

		// this data is just to show how you can pass your own custom data through InitSecurityHandler
		void* custom_data = const_cast<char*>("my custom pointer");

		// 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.InitSecurityHandler(custom_data))
		{
			cout << "Document authentication error..." << endl;
			cout << "The password is not valid." << endl;
		}
		else 
		{
			cout << "\nThe password is correct! Document can now be used for reading and editing" << endl;

			// Remove the password security and save the changes to a new file.
			doc.RemoveSecurity();
			doc.Save((output_path + "secured_nomore2.pdf").c_str(), 0, NULL);
			cout << "Done. Result saved in secured_nomore2.pdf" << endl;
		}
	}
	catch(Common::Exception& e) {
		cout << e << endl;
		ret = 1;
	}
	catch(...) {
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	cout << "-------------------------------------------------" << endl;
	cout << "Tests completed." << endl;

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------
// 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.
//---------------------------------------------------------------------------------------
const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  exports.runEncTest = () => {

    const main = async () => {
      let ret = 0;
      // Relative path to the folder containing test files.
      const inputPath = '../TestFiles/';
      const outputPath = inputPath + 'Output/';
      // Example 1:
      // secure a PDF document with password protection and adjust permissions
      try {
        // Open the test file
        console.log('-------------------------------------------------/nSecuring an existing document...');
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'fish.pdf');
        if (!(await doc.initSecurityHandler())) {
          console.log('Document authentication error...');
          ret = 1;
        }

        const performOperation = true; // optional parameter

        // 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'
        // Results in fish.pdf becoming a pair of feathers.
        if (performOperation) {
          console.log('Replacing the content stream, use Flate compression...');
          // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
          const pageTrailer = await doc.getTrailer();
          const pageRoot = await pageTrailer.get('Root');
          const pageRootValue = await pageRoot.value();
          const pages = await pageRootValue.get('Pages');
          const pagesVal = await pages.value();
          const kids = await pagesVal.get('Kids');
          const kidsVal = await kids.value();
          const pageDict = await kidsVal.getAt(0);

          const embedFile = await PDFNet.Filter.createMappedFileFromUString(inputPath + 'my_stream.txt');
          const mystm = await PDFNet.FilterReader.create(embedFile);

          const flateEncode = await PDFNet.Filter.createFlateEncode();

          const indStream = await doc.createIndirectStreamFromFilter(mystm, flateEncode);
          await pageDict.put('Contents', indStream);
        }

        // Encrypt the document
        // Apply a new security handler with given security settings.
        // In order to open saved PDF you will need a user password 'test'.
        const newHandler = await PDFNet.SecurityHandler.createDefault();

        // Set a new password required to open a document
        newHandler.changeUserPasswordUString('test');

        // Set Permissions
        newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_print, true);
        await newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_extract_content, false);

        // Note: document takes the ownership of newHandler.
        doc.setSecurityHandler(newHandler);

        // Save the changes
        console.log('Saving modified file...');
        await doc.save(outputPath + 'secured.pdf', 0);
        console.log('Done. Result saved in secured.pdf');
      } catch (err) {
        console.log(err);
        console.log(err.stack);
        ret = 1;
      }

      // Example 2:
      // Opens an encrypted PDF document and removes its security.
      try {
        console.log('-------------------------------------------------');
        console.log('Open the password protected document from the first example...');
        const securedDoc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'secured.pdf');
        console.log('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 (!(await securedDoc.initStdSecurityHandlerUString('test'))) {
          console.log('Document authentication error.../nThe password is not valid.');
          ret = 1;
          return ret;
        }

        console.log('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.
        securedDoc.removeSecurity();
        await securedDoc.save(outputPath + 'secured_nomore1.pdf', 0);
        console.log('Done. Result saved in secured_nomore1.pdf');

        /*
        const hdlr = await securedDoc.getSecurityHandler();

        console.log('Document Open Password: ' + (await hdlr.isUserPasswordRequired()));
        console.log('Permissions Password: ' + (await hdlr.isMasterPasswordRequired()));
        console.log('Permissions: ');
        console.log("\tHas 'owner' permissions: " + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_owner)));

        console.log('\tOpen and decrypt the document: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_open)));
        console.log('\tAllow content extraction: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_extract_content)));
        console.log('\tAllow full document editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_modify)));
        console.log('\tAllow printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print)));
        console.log('\tAllow high resolution printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print_high)));
        console.log('\tAllow annotation editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_mod_annot)));
        console.log('\tAllow form fill: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_fill_forms)));
        console.log('\tAllow content extraction for accessibility: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_access_support)));
        console.log('\tAllow document assembly: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_assemble_doc)));
        */
      } catch (err) {
        console.log(err.stack);
        ret = 1;
      }

      // Example 3:
      // Encrypt/Decrypt a PDF using PDFTron custom security handler
      try {
        console.log('-------------------------------------------------');
        console.log('Encrypt a document using PDFTron Custom Security handler with a custom id and password...');
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + "BusinessCardTemplate.pdf");

        // Create PDFTron custom security handler with a custom id. Replace this with your own integer
        const custom_id = 123456789;
        const custom_handler = await PDFNet.PDFTronCustomSecurityHandler.create(custom_id);

        // Add a password to the custom security handler
        const pass = 'test';
        await custom_handler.changeUserPasswordUString(pass);

        // Save the encrypted document
        doc.setSecurityHandler(custom_handler);
        await doc.save(outputPath + 'BusinessCardTemplate_enc.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);

        console.log('Decrypt the PDFTron custom security encrypted document above...');
        // Register the PDFTron Custom Security handler with the same custom id used in encryption
        await PDFNet.addPDFTronCustomHandler(custom_id);

        const doc_enc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'BusinessCardTemplate_enc.pdf');
        doc_enc.initStdSecurityHandlerUString(pass);
        doc_enc.removeSecurity();
        // Save the decrypted document
        await doc_enc.save(outputPath + 'BusinessCardTemplate_enc_dec.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        console.log('Done. Result saved in BusinessCardTemplate_enc_dec.pdf');
      } catch (err) {
        console.log(err.stack);
        ret = 1;
      }

      console.log('-------------------------------------------------');
      console.log('Tests completed.');

      return ret;
    };

    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
  };
  exports.runEncTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=EncTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

//---------------------------------------------------------------------------------------
// 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.
//---------------------------------------------------------------------------------------
	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
	
	// Relative path to the folder containing the test files.
	$input_path = getcwd()."/../../TestFiles/";
	$output_path = $input_path."Output/";

	// Example 1: 
	// secure a PDF document with password protection and adjust permissions

	// Open the test file
	echo "Securing an existing document ...\n";
	$doc = new PDFDoc($input_path."fish.pdf");
	$doc->InitSecurityHandler();

	// 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
	{
		echo "Replacing the content stream, use Flate compression...\n";

		// Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
		$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.
		$embed_file = new MappedFile($input_path."my_stream.txt");
		$mystm = new FilterReader($embed_file);
		$page_dict->Put("Contents", $doc->CreateIndirectStream($mystm, new FlateEncode(new Filter())));
	}

	//encrypt the document
	
	// Apply a new security handler with given security settings. 
	// In order to open saved PDF you will need a user password 'test'.
	$new_handler = new SecurityHandler();

	// Set a new password required to open a document
	$user_password="test";
	$new_handler->ChangeUserPassword($user_password);

	// Set Permissions
	$new_handler->SetPermission (SecurityHandler::e_print, true);
	$new_handler->SetPermission (SecurityHandler::e_extract_content, false);

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

	// Save the changes.
	echo "Saving modified file...\n";
	$doc->Save($output_path."secured.pdf", 0);
	$doc->Close();

	// Example 2:
	// Opens an encrypted PDF document and removes its security.

	$doc = new PDFDoc($output_path."secured.pdf");

	//If the document is encrypted prompt for the password
	if (!$doc->InitSecurityHandler()) 
	{
		$success=false;
		echo "The password is: test\n";
		for($count=0; $count<3;$count++)
		{
			echo "A password required to open the document.\n"
				."Please enter the password:";
			
			$password = trim(fgets(STDIN));
			if($doc->InitStdSecurityHandler($password, strlen($password)))
			{
				$success=true;
				echo "The password is correct.\n";
				break;
			}
			else if($count<3)
			{
				echo "The password is incorrect, please try again\n";
			}
		}
		if(!$success)
		{
			echo "Document authentication error....\n";
			PDFNet::Terminate();
			return;
		}

		$hdlr = $doc->GetSecurityHandler(); 
		echo "Document Open Password: ".$hdlr->IsUserPasswordRequired()."\n";
		echo "Permissions Password: ".$hdlr->IsMasterPasswordRequired()."\n";
		echo "Permissions: " 
			."\n\tHas 'owner' permissions: ".$hdlr->GetPermission(SecurityHandler::e_owner)
			."\n\tOpen and decrypt the document: ".$hdlr->GetPermission(SecurityHandler::e_doc_open)
			."\n\tAllow content extraction: ".$hdlr->GetPermission(SecurityHandler::e_extract_content) 
			."\n\tAllow full document editing: ".$hdlr->GetPermission(SecurityHandler::e_doc_modify) 
			."\n\tAllow printing: ".$hdlr->GetPermission(SecurityHandler::e_print) 
			."\n\tAllow high resolution printing: ".$hdlr->GetPermission(SecurityHandler::e_print_high) 
			."\n\tAllow annotation editing: ".$hdlr->GetPermission(SecurityHandler::e_mod_annot) 
			."\n\tAllow form fill: ".$hdlr->GetPermission(SecurityHandler::e_fill_forms) 
			."\n\tAllow content extraction for accessibility: ".$hdlr->GetPermission(SecurityHandler::e_access_support) 
			."\n\tAllow document assembly: ".$hdlr->GetPermission(SecurityHandler::e_assemble_doc) 
			."\n";   
	}

	// remove all security on the document
	$doc->RemoveSecurity();
	$doc->Save($output_path."not_secured.pdf", 0);
	$doc->Close();

	// Example 3: 
	echo "-------------------------------------------------\n";
	echo "Encrypt a document using PDFTron Custom Security handler with a custom id and password...\n";
	$doc = new PDFDoc($input_path . "BusinessCardTemplate.pdf");

	// Create PDFTron custom security handler with a custom id. Replace this with your own integer
	$custom_id = 123456789;
	$custom_handler = new PDFTronCustomSecurityHandler($custom_id);

	// Add a password to the custom security handler
	$pass = "test";
	$custom_handler->ChangeUserPassword($pass);

	// Save the encrypted document
	$doc->SetSecurityHandler($custom_handler);
	$doc->Save($output_path . "BusinessCardTemplate_enc.pdf", 0);
	$doc->Close();

	echo "Decrypt the PDFTron custom security encrypted document above...\n";
	// Register the PDFTron Custom Security handler with the same custom id used in encryption
	PDFNet::AddPDFTronCustomHandler($custom_id);

	$doc_enc = new PDFDoc($output_path . "BusinessCardTemplate_enc.pdf");
	$doc_enc->InitStdSecurityHandler($pass);
	$doc_enc->RemoveSecurity();
	// Save the decrypted document
	$doc_enc->Save($output_path . "BusinessCardTemplate_enc_dec.pdf", 0);
	$doc->Close();
	PDFNet::Terminate();
	echo "Done. Result saved in BusinessCardTemplate_enc_dec.pdf\n";
	echo "-------------------------------------------------\n";
	echo "Test Completed.\n";
?>
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

#---------------------------------------------------------------------------------------
# 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.
#---------------------------------------------------------------------------------------

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    output_path = "../../TestFiles/Output/"
    
    # Example 1: 
    # secure a PDF document with password protection and adjust permissions
    
    # Open the test file
    print("Securing an existing document...")
    
    doc = PDFDoc(input_path + "fish.pdf")
    doc.InitSecurityHandler()
    
    # 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
        print("Replacing the content stream, use Flate compression...")
        
        # Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
        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.
        embed_file = MappedFile(input_path + "my_stream.txt")
        mystm = FilterReader(embed_file)
        page_dict.Put("Contents", doc.CreateIndirectStream(mystm, FlateEncode(Filter())))
        
    # encrypt the document
    
    # Apply a new security handler with given security settings.
    # In order to open saved PDF you will need a user password 'test'.
    new_handler = SecurityHandler()
    
    # Set a new password required to open a document
    user_password = "test"
    new_handler.ChangeUserPassword(user_password)
    
    # Set permissions
    new_handler.SetPermission(SecurityHandler.e_print, True)
    new_handler.SetPermission(SecurityHandler.e_extract_content, False)
    
    # Note: document takes the ownership of new_handler.
    doc.SetSecurityHandler(new_handler)
    
    # save the changes.
    print("Saving modified file...")
    doc.Save(output_path + "secured.pdf", 0)
    doc.Close()
    
    # Example 2:
    # Opens an encrypted PDF document and removes its security.
    
    doc = PDFDoc(output_path + "secured.pdf")
    
    # If the document is encrypted prompt for the password
    if not doc.InitSecurityHandler():
        success = False
        print("The password is: test")
        count = 0
        while count < 3:
            print("A password required to open the document.")
            if sys.version_info.major >= 3:
                password = input("Please enter the password: \n")
            else:
                password = raw_input("Please enter the password: \n")
                
            if doc.InitStdSecurityHandler(password, len(password)):
                success = True
                print("The password is correct.")
                break
            elif count < 3:
                print("The password is incorrect, please try again")
            count = count + 1
            
        if not success:
            print("Document authentication error....")
            return
        
        hdlr = doc.GetSecurityHandler()
        print("Document Open Password: " + str(hdlr.IsUserPasswordRequired()))
        print("Permissions Password: " + str(hdlr.IsMasterPasswordRequired()))
        print(("Permissions: " 
                + "\n\tHas 'owner' permissions: " + str(hdlr.GetPermission(SecurityHandler.e_owner))
                + "\n\tOpen and decrypt the document: " + str(hdlr.GetPermission(SecurityHandler.e_doc_open))
                + "\n\tAllow content extraction: " + str(hdlr.GetPermission(SecurityHandler.e_extract_content)) 
                + "\n\tAllow full document editing: " + str(hdlr.GetPermission(SecurityHandler.e_doc_modify) )
                + "\n\tAllow printing: " + str(hdlr.GetPermission(SecurityHandler.e_print)) 
                + "\n\tAllow high resolution printing: " + str(hdlr.GetPermission(SecurityHandler.e_print_high)) 
                + "\n\tAllow annotation editing: " + str(hdlr.GetPermission(SecurityHandler.e_mod_annot)) 
                + "\n\tAllow form fill: " + str(hdlr.GetPermission(SecurityHandler.e_fill_forms)) 
                + "\n\tAllow content extraction for accessibility: " + str(hdlr.GetPermission(SecurityHandler.e_access_support)) 
                + "\n\tAllow document assembly: " + str(hdlr.GetPermission(SecurityHandler.e_assemble_doc))))
        
    # remove all security on the document
    doc.RemoveSecurity()
    doc.Save(output_path + "not_secured.pdf", 0)
    doc.Close()

    # Example 3:
    # Encrypt/Decrypt a PDF using PDFTron custom security handler
    print("-------------------------------------------------")
    print("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
    doc = PDFDoc(input_path + "BusinessCardTemplate.pdf")

    # Create PDFTron custom security handler with a custom id. Replace this with your own integer
    custom_id = 123456789
    custom_handler = PDFTronCustomSecurityHandler(custom_id)

    # Add a password to the custom security handler
    password = "test"
    custom_handler.ChangeUserPassword(password)

    # Save the encrypted document
    doc.SetSecurityHandler(custom_handler)
    doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0)
    doc.Close()

    print("Decrypt the PDFTron custom security encrypted document above...")
    # Register the PDFTron Custom Security handler with the same custom id used in encryption
    PDFNet.AddPDFTronCustomHandler(custom_id)

    doc_enc = PDFDoc(output_path + "BusinessCardTemplate_enc.pdf")
    doc_enc.InitStdSecurityHandler(password)
    doc_enc.RemoveSecurity()
    # Save the decrypted document
    doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0)
    doc_enc.Close()
    PDFNet.Terminate()
    print("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
    print("-------------------------------------------------");
    print("Test completed.")
        
if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#---------------------------------------------------------------------------------------
# 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.
#---------------------------------------------------------------------------------------

	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Relative path to the folder containing the test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"
	
	# Example 1: 
	# secure a PDF document with password protection and adjust permissions
	
	# Open the test file
	puts "Securing an existing document..."
	
	doc = PDFDoc.new(input_path + "fish.pdf")
	doc.InitSecurityHandler()
	
	# 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
		puts "Replacing the content stream, use Flate compression..."
		
		# Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
		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.
		embed_file = MappedFile.new(input_path + "my_stream.txt")
		mystm = FilterReader.new(embed_file)
		page_dict.Put("Contents", doc.CreateIndirectStream(mystm, FlateEncode.new(Filter.new())))
	end
		
	# encrypt the document
	
	# Apply a new security handler with given security settings.
	# In order to open saved PDF you will need a user password 'test'.
	new_handler = SecurityHandler.new()
	
	# Set a new password required to open a document
	user_password = "test"
	new_handler.ChangeUserPassword(user_password)
	
	# Set permissions
	new_handler.SetPermission(SecurityHandler::E_print, true)
	new_handler.SetPermission(SecurityHandler::E_extract_content, false)
	
	# Note: document takes the ownership of new_handler.
	doc.SetSecurityHandler(new_handler)
	
	# save the changes.
	puts "Saving modified file..."
	doc.Save(output_path + "secured.pdf", 0)
	doc.Close()
	
	# Example 2:
	# Opens an encrypted PDF document and removes its security.
	
	doc = PDFDoc.new(output_path + "secured.pdf")
	
	# If the document is encrypted prompt for the password
	if !doc.InitSecurityHandler()
		success = false
		puts "The password is: test"
		count = 0
		while count < 3 do
			puts "A password required to open the document."
			puts "Please enter the password:"
			password = gets.chomp
			if doc.InitStdSecurityHandler(password, password.length)
				success = true
				puts "The password is correct."
				break
			elsif count < 3
				puts "The password is incorrect, please try again"
			end
			count = count + 1
		end
			
		if !success
			puts "Document authentication error...."
			return
		end
		
		hdlr = doc.GetSecurityHandler()
		puts "Document Open Password: " + hdlr.IsUserPasswordRequired().to_s()
		puts "Permissions Password: " + hdlr.IsMasterPasswordRequired().to_s()
		puts ("Permissions:  " +
				"\n\tHas 'owner' permissions: " + hdlr.GetPermission(SecurityHandler::E_owner).to_s() +
				"\n\tOpen and decrypt the document: " + hdlr.GetPermission(SecurityHandler::E_doc_open).to_s() +
				"\n\tAllow content extraction: " + hdlr.GetPermission(SecurityHandler::E_extract_content).to_s() +
				"\n\tAllow full document editing: " + hdlr.GetPermission(SecurityHandler::E_doc_modify).to_s() +
				"\n\tAllow printing: " + hdlr.GetPermission(SecurityHandler::E_print).to_s() +
				"\n\tAllow high resolution printing: " + hdlr.GetPermission(SecurityHandler::E_print_high).to_s() +
				"\n\tAllow annotation editing: " + hdlr.GetPermission(SecurityHandler::E_mod_annot).to_s() +
				"\n\tAllow form fill: " + hdlr.GetPermission(SecurityHandler::E_fill_forms).to_s() +
				"\n\tAllow content extraction for accessibility: " + hdlr.GetPermission(SecurityHandler::E_access_support).to_s() +
				"\n\tAllow document assembly: " + hdlr.GetPermission(SecurityHandler::E_assemble_doc).to_s())
	end
		
	# remove all security on the document
	doc.RemoveSecurity()
	doc.Save(output_path + "not_secured.pdf", 0)
	doc.Close()

	# Example 3:
	# Encrypt/Decrypt a PDF using PDFTron custom security handler
	puts "-------------------------------------------------"
	puts "Encrypt a document using PDFTron Custom Security handler with a custom id and password..."
	doc = PDFDoc.new(input_path + "BusinessCardTemplate.pdf")

	# Create PDFTron custom security handler with a custom id. Replace this with your own integer
	custom_id = 123456789
	custom_handler = PDFTronCustomSecurityHandler.new(custom_id)

	# Add a password to the custom security handler
	password = "test"
	custom_handler.ChangeUserPassword(password)

	# Save the encrypted document
	doc.SetSecurityHandler(custom_handler)
	doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0)
	doc.Close()

	puts "Decrypt the PDFTron custom security encrypted document above..."
	# Register the PDFTron Custom Security handler with the same custom id used in encryption
	PDFNet.AddPDFTronCustomHandler(custom_id)

	doc_enc = PDFDoc.new(output_path + "BusinessCardTemplate_enc.pdf")
	doc_enc.InitStdSecurityHandler(password)
	doc_enc.RemoveSecurity()
	# Save the decrypted document
	doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0)
	doc_enc.Close()
	PDFNet.Terminate
	puts "Done. Result saved in BusinessCardTemplate_enc_dec.pdf"
	puts "-------------------------------------------------"
	puts "Test completed."
```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'---------------------------------------------------------------------------------------
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
' Consult legal.txt regarding legal and license information.
'---------------------------------------------------------------------------------------
Imports System

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

'---------------------------------------------------------------------------------------
' 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.
'---------------------------------------------------------------------------------------
Module EncTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub

    ' A custom security handler used to obtain document password dynamically via user feedback. 
    Public Class MySecurityHandler
        Inherits StdSecurityHandler

        Sub New(ByVal key_len As Int32, ByVal enc_code As Int32)
            MyBase.New(key_len, enc_code)
        End Sub

        Sub New(ByVal s As MySecurityHandler)
            MyBase.New(s)
        End Sub

        ' In this callback ask the user for password/authorization data. 
        ' This may invlove a dialog box used to collect authorization data or something else.
        Public Overrides Function GetAuthorizationData(ByVal p As SecurityHandler.Permission) As Boolean
            Console.WriteLine("The input file requires user password.")
            Console.WriteLine("Please enter the password:")
            Dim pass As String = Console.ReadLine()
            InitPassword(pass)
            Return True
        End Function

        ' This callback could be used to customize security handler preferences.
        Public Overloads Function EditSecurityData(ByVal doc As SDFDoc) As Boolean
            Return False
        End Function

        ' This callback is used when authorization process fails. 
        Public Overloads Sub AuthorizeFailed()
            Console.WriteLine("Authorize failed...")
        End Sub

        Public Shared Function Create(ByVal name As String, ByVal key_len As Int32, ByVal enc_code As Int32) As SecurityHandler
            Return New MySecurityHandler(key_len, enc_code)
        End Function

        Public Overloads Function Clone() As SecurityHandler
            Return New MySecurityHandler(Me)
        End Function

    End Class


    Sub Main()

        PDFNet.Initialize(PDFTronLicense.Key)

        ' Relative path to the folder containing test files.
        Dim input_path As String = "../../../../TestFiles/"
        Dim output_path As String = "../../../../TestFiles/Output/"

        ' 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 doc As PDFDoc = New PDFDoc(input_path + "fish.pdf")
                If Not doc.InitSecurityHandler() Then
                    Console.WriteLine("Document authentication error...")
                    Return
                End If

                ' 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) Then              ' Optional
                    Console.WriteLine("Replacing the content stream, use flate compression...")

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

                    ' Embed a custom stream (file mystream.txt) using Flate compression.
                    Dim embed_file As MappedFile = New MappedFile(input_path + "my_stream.txt")
                    Dim mystm As FilterReader = New FilterReader(embed_file)
                    page_dict.Put("Contents", doc.CreateIndirectStream(mystm))
                    embed_file.Close()
                End If

                ' Apply a new security handler with given security settings. 
                ' In order to open saved PDF you will need a user password 'test'.
                Dim new_handler As StdSecurityHandler = New StdSecurityHandler

                ' Set a new password required to open a document
                Dim my_password As String = "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(output_path + "secured.pdf", 0)
            End Using
            Console.WriteLine("Done. Result saved in secured.pdf...")
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        ' 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 doc As PDFDoc = New PDFDoc(output_path + "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 Not doc.InitStdSecurityHandler("test") Then
                    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.SetSecurityHandler(Nothing)
                    doc.Save(output_path + "secured_nomore1.pdf", 0)
                    Console.WriteLine("Done. Result saved in secured_nomore1.pdf")
                End If
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        ' Example 3: 
        ' Encrypt/Decrypt a PDF using PDFTron custom security handler
        Try
            Console.WriteLine("-------------------------------------------------")
            Console.WriteLine("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
            Dim doc As PDFDoc = New PDFDoc(input_path & "BusinessCardTemplate.pdf")

            ' Create PDFTron custom security handler with a custom id. Replace this with your own integer
            Dim custom_id As Integer = 123456789
            Dim custom_handler As PDFTronCustomSecurityHandler = New PDFTronCustomSecurityHandler(custom_id)
            ' Add a password to the custom security handler
            Dim pass As String = "test"
            custom_handler.ChangeUserPassword(pass)
            ' Save the encrypted document
            doc.SetSecurityHandler(custom_handler)
            doc.Save(output_path & "BusinessCardTemplate_enc.pdf", 0)
            Console.WriteLine("Decrypt the PDFTron custom security encrypted document above...")
            ' Register the PDFTron Custom Security handler with the same custom id used in encryption
            PDFNet.AddPDFTronCustomHandler(custom_id)
            Dim doc_enc As PDFDoc = New PDFDoc(output_path & "BusinessCardTemplate_enc.pdf")
            doc_enc.InitStdSecurityHandler(pass)
            doc_enc.RemoveSecurity()
            ' Save the decrypted document
            doc_enc.Save(output_path & "BusinessCardTemplate_enc_dec.pdf", 0)
            Console.WriteLine("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        ' Example 4: Reading password protected document with user feedback.
        Try
            ' Register standard security. Reguired only once per application session.
            Dim del As CreateDelegate = New CreateDelegate(AddressOf MySecurityHandler.Create)
            SecurityManagerSingleton.Instance().RegisterSecurityHandler("Standard", _
             New SecurityDescriptor("Standard Security", del))

            Console.WriteLine("-------------------------------------------------")
            Console.WriteLine("Open the password protected document from the first example...")
            Using doc As PDFDoc = New PDFDoc(output_path + "secured.pdf")     ' Open the encrypted document that we saved in the first example.
                Console.WriteLine("Initializing security handler. The password will now be collected from the user")
                Console.WriteLine("Enter 'test' as the password.")

                ' 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 Not doc.InitSecurityHandler() Then
                    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.SetSecurityHandler(Nothing)
                    doc.Save(output_path + "secured_nomore2.pdf", 0)
                    Console.WriteLine("Done. Result saved in secured_nomore2.pdf")
                End If
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        PDFNet.Terminate()
        Console.WriteLine("-------------------------------------------------")
        Console.WriteLine("Tests completed.")
    End Sub
End Module
```

{% 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
