> 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/ios/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 Obj-C

Sample Obj-C code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our [iOS SDK](/ios/guides.md).

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

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

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

//---------------------------------------------------------------------------------------
// 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[])
{
    @autoreleasepool {
        int ret = 0;
        [PTPDFNet Initialize: 0];

        // Example 1: 
        // secure a PDF document with password protection and adjust permissions 
        
        @try
        {
            // Open the test file
            NSLog(@"Securing an existing document ...");
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/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 (NO)  // Optional
            {
                NSLog(@"Replacing the content stream, use Flate compression...");

                // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
                PTObj *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.
                PTMappedFile *embed_file = [[PTMappedFile alloc] initWithFilename: @"../../TestFiles/mystream.txt"];
                PTFilterReader *mystm = [[PTFilterReader alloc] initWithFilter: embed_file];
                PTFlateEncode *encode = [[PTFlateEncode alloc] initWithInput_filter: [[PTFilter alloc] init] compression_level: -1 buf_sz: 256];
                [page_dict Put: @"Contents" obj: [doc CreateIndirectStream: mystm filter_chain: encode]];
            }

            //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'.
            PTSecurityHandler *new_handler = [[PTSecurityHandler alloc] init];

            // Set a new password required to open a document
            NSString* user_password=@"test";
            [new_handler ChangeUserPassword: user_password];

            // Set Permissions
            [new_handler SetPermission: e_ptprint value: YES];
            [new_handler SetPermission: e_ptextract_content value: NO];

            // Note: document takes the ownership of new_handler.
            [doc SetSecurityHandler: new_handler];

            // Save the changes.
            NSLog(@"Saving modified file...");
            [doc SaveToFile: @"../../TestFiles/Output/secured.pdf" flags: 0];

        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }

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

        @try
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/secured.pdf"];

            //If the document is encrypted prompt for the password
            if (![doc InitSecurityHandler]) 
            {
                bool success=NO;
                NSLog(@"The password is: test");
                int count;
                for(count=0; count<3;count++)
                {
                    char input[255];
                    NSLog(@"A password required to open the document.");
                    NSLog(@"Please enter the password:");
                    //scanf("%c", &input);
                    NSString *password = @"test";
    //                int i = 0;
    //                for (; i < 254; i++) {
    //                    if (input[i] == '\0') {
    //                        break;
    //                    }
    //                    [password stringByAppendingFormat: @"%c", input[i]];
    //                }
                
                    if([doc InitStdSecurityHandler: password])
                    {
                        success=true;
                        NSLog(@"The password is correct.");
                        break;
                    }
                    else if(count<3)
                    {
                        NSLog(@"The password is incorrect, please try again.");
                    }
                }
                if(!success)
                {
                    NSLog(@"Document authentication error....");
                    ret = 1;
                    return ret;
                }

                PTSecurityHandler *hdlr = [doc GetSecurityHandler]; 
                NSLog(@"Document Open Password: %d", [hdlr IsUserPasswordRequired]);
                NSLog(@"Permissions Password: %d", [hdlr IsMasterPasswordRequired]);
                NSLog(@"Permissions: ");
                NSLog(@"    Has 'owner' permissions: %d", [hdlr GetPermission: e_ptowner]);
                NSLog(@"    Open and decrypt the document: %d", [hdlr GetPermission: e_ptdoc_open]);
                NSLog(@"    Allow content extraction: %d", [hdlr GetPermission: e_ptextract_content]); 
                NSLog(@"    Allow full document editing: %d", [hdlr GetPermission: e_ptdoc_modify]);
                NSLog(@"    Allow printing: %d", [hdlr GetPermission: e_ptprint]); 
                NSLog(@"    Allow high resolution printing: %d", [hdlr GetPermission: e_ptprint_high]); 
                NSLog(@"    Allow annotation editing: %d", [hdlr GetPermission: e_ptmod_annot]);
                NSLog(@"    Allow form fill: %d", [hdlr GetPermission: e_ptfill_forms]);
                NSLog(@"    Allow content extraction for accessibility: %d", [hdlr GetPermission: e_ptaccess_support]);
                NSLog(@"    Allow document assembly: %d", [hdlr GetPermission: e_ptassemble_doc]);   
            }

            //remove all security on the document
            [doc RemoveSecurity];
            [doc SaveToFile: @"../../TestFiles/Output/not_secured.pdf" flags: 0];

        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }

    // Example 3:
    // Encrypt/Decrypt a PDF using PDFTron custom security handler

        @try
        {
            NSLog(@"-------------------------------------------------");
            NSLog(@"Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/BusinessCardTemplate.pdf"];

            // Create PDFTron custom security handler with a custom id. Replace this with your own integer
            unsigned int custom_id = 123456789;
            PTSecurityHandler* custom_handler = [[PTPDFTronCustomSecurityHandler alloc] initWithCustom_id : custom_id];

            // Add a password to the custom security handler
            NSString *pass = @"test";
            [custom_handler ChangeUserPassword: pass];

            [doc SetSecurityHandler: custom_handler];

            // Save the changes.
            [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf" flags: 0];


            NSLog(@"Decrypt the PDFTron custom security encrypted document above...");
            // Register the PDFTron Custom Security handler with the same custom id used in encryption
            [PTPDFNet AddPDFTronCustomHandler : custom_id];
            PTPDFDoc *doc_enc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf"];
            [doc_enc InitStdSecurityHandler : pass];
            [doc RemoveSecurity];
            // Save the decrypted document
            [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc_dec.pdf" flags: 0];
            NSLog(@"Done. Result saved in BusinessCardTemplate_enc_dec.pdf");

        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }
        [PTPDFNet Terminate: 0];
        return ret;
    }
}
```

{% endcode %}
{% endtab %}

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

```swift
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

//---------------------------------------------------------------------------------------
// 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 runEncTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        
        // Example 1:
        // secure a PDF document with password protection and adjust permissions

        do {
            try PTPDFNet.catchException {
                // Open the test file
                print("Securing an existing document ...")
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "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 false {
//                    print("Replacing the content stream, use Flate compression...")
//                    
//                    // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
//                    let page_dict: PTObj = doc.getTrailer().get("Root").value().get("Pages").value().get("Kids").value().getAt(0)
//                    
//                    // Embed a custom stream (file mystream.txt) using Flate compression.
//                    let embed_file = PTMappedFile(filename: Bundle.main.path(forResource: "my_stream", ofType: "txt"))
//                    let mystm = PTFilterReader(filter: embed_file)
//                    let encode = PTFlateEncode(input_filter: PTFilter(), compression_level: -1, buf_sz: 256)
//                    page_dict.put("Contents", obj: doc.createIndirectStream(mystm, filter_chain: encode))
                }
                
                //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'.
                let new_handler: PTSecurityHandler = PTSecurityHandler()
                
                // Set a new password required to open a document
                let user_password = "test"
                new_handler.changeUserPassword(user_password)
                
                // Set Permissions
                new_handler.setPermission(e_ptprint, value: true)
                new_handler.setPermission(e_ptextract_content, value: false)
                
                // Note: document takes the ownership of new_handler.
                doc.setSecurityHandler(new_handler)
                
                // Save the changes.
                print("Saving modified file...")
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path, flags: 0)

            }
        } catch let e as NSError {
            print("Uncaught exception: \(e)")
            ret = 1
        }
        
        // Example 2:
        // Opens an encrypted PDF document and removes its security.
        
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path)
                
                //If the document is encrypted prompt for the password
                if !doc.initSecurityHandler() {
                    var success = false
                    print("The password is: test")
                    for count in 0..<3 {
                        print("A password is required to open the document.")
                        print("Please enter the password:")
                        //let input = readLine()
                        let password = "test"
                        //for i in 0..<255 {
                        //    let value = input[input.index(input.startIndex, offsetBy: i)]
                        //    if value == "\0" {
                        //        break
                        //    }
                        //    password += ("\(value)")
                        //}
                        
                        if doc.initStdSecurityHandler(password) {
                            success = true
                            print("The password is correct.")
                            break
                        }
                        else if count < 3 {
                            print("The password is incorrect, please try again.")
                        }
                    }
                    if !success {
                        print("Document authentication error....")
                        ret = 1
                        return
                    }
                    
                    let hdlr: PTSecurityHandler = doc.getSecurityHandler()
                    print("Document Open Password: \(hdlr.isUserPasswordRequired())")
                    print("Permissions Password: \(hdlr.isMasterPasswordRequired())")
                    print("Permissions: ")
                    print("    Has 'owner' permissions: \(hdlr.getPermission(e_ptowner))")
                    print("    Open and decrypt the document: \(hdlr.getPermission(e_ptdoc_open))")
                    print("    Allow content extraction: \(hdlr.getPermission(e_ptextract_content))")
                    print("    Allow full document editing: \(hdlr.getPermission(e_ptdoc_modify))")
                    print("    Allow printing: \(hdlr.getPermission(e_ptprint))")
                    print("    Allow high resolution printing: \(hdlr.getPermission(e_ptprint_high))")
                    print("    Allow annotation editing: \(hdlr.getPermission(e_ptmod_annot))")
                    print("    Allow form fill: \(hdlr.getPermission(e_ptfill_forms))")
                    print("    Allow content extraction for accessibility: \(hdlr.getPermission(e_ptaccess_support))")
                    print("    Allow document assembly: \(hdlr.getPermission(e_ptassemble_doc))")
                }
                
                //remove all security on the document
                doc.removeSecurity()
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("not_secured.pdf").path, flags: 0)
            }
        } catch let e as NSError {
            print("Uncaught exception: \(e)")
            ret = 1
        }
        
        return ret
    }
}
```

{% 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/ios/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.
