Encryption

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.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#import <OBJC/PDFNetOBJC.h>
7#import <Foundation/Foundation.h>
8
9//---------------------------------------------------------------------------------------
10// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
11// sets a new SecurityHandler. The sample also illustrates how password protection can
12// be removed from an existing PDF document.
13//---------------------------------------------------------------------------------------
14int main(int argc, char *argv[])
15{
16 @autoreleasepool {
17 int ret = 0;
18 [PTPDFNet Initialize: 0];
19
20 // Example 1:
21 // secure a PDF document with password protection and adjust permissions
22
23 @try
24 {
25 // Open the test file
26 NSLog(@"Securing an existing document ...");
27 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/fish.pdf"];
28 [doc InitSecurityHandler];
29
30 // Perform some operation on the document. In this case we use low level SDF API
31 // to replace the content stream of the first page with contents of file 'my_stream.txt'
32 if (NO) // Optional
33 {
34 NSLog(@"Replacing the content stream, use Flate compression...");
35
36 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
37 PTObj *page_dict = [[[[[[[[doc GetTrailer] Get: @"Root"] Value] Get: @"Pages"] Value ] Get: @"Kids"] Value] GetAt: 0];
38
39 // Embed a custom stream (file mystream.txt) using Flate compression.
40 PTMappedFile *embed_file = [[PTMappedFile alloc] initWithFilename: @"../../TestFiles/mystream.txt"];
41 PTFilterReader *mystm = [[PTFilterReader alloc] initWithFilter: embed_file];
42 PTFlateEncode *encode = [[PTFlateEncode alloc] initWithInput_filter: [[PTFilter alloc] init] compression_level: -1 buf_sz: 256];
43 [page_dict Put: @"Contents" obj: [doc CreateIndirectStream: mystm filter_chain: encode]];
44 }
45
46 //encrypt the document
47
48
49 // Apply a new security handler with given security settings.
50 // In order to open saved PDF you will need a user password 'test'.
51 PTSecurityHandler *new_handler = [[PTSecurityHandler alloc] init];
52
53 // Set a new password required to open a document
54 NSString* user_password=@"test";
55 [new_handler ChangeUserPassword: user_password];
56
57 // Set Permissions
58 [new_handler SetPermission: e_ptprint value: YES];
59 [new_handler SetPermission: e_ptextract_content value: NO];
60
61 // Note: document takes the ownership of new_handler.
62 [doc SetSecurityHandler: new_handler];
63
64 // Save the changes.
65 NSLog(@"Saving modified file...");
66 [doc SaveToFile: @"../../TestFiles/Output/secured.pdf" flags: 0];
67
68 }
69 @catch(NSException *e)
70 {
71 NSLog(@"%@", e.reason);
72 ret = 1;
73 }
74
75 // Example 2:
76 // Opens an encrypted PDF document and removes its security.
77
78 @try
79 {
80 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/secured.pdf"];
81
82 //If the document is encrypted prompt for the password
83 if (![doc InitSecurityHandler])
84 {
85 bool success=NO;
86 NSLog(@"The password is: test");
87 int count;
88 for(count=0; count<3;count++)
89 {
90 char input[255];
91 NSLog(@"A password required to open the document.");
92 NSLog(@"Please enter the password:");
93 //scanf("%c", &input);
94 NSString *password = @"test";
95 // int i = 0;
96 // for (; i < 254; i++) {
97 // if (input[i] == '\0') {
98 // break;
99 // }
100 // [password stringByAppendingFormat: @"%c", input[i]];
101 // }
102
103 if([doc InitStdSecurityHandler: password])
104 {
105 success=true;
106 NSLog(@"The password is correct.");
107 break;
108 }
109 else if(count<3)
110 {
111 NSLog(@"The password is incorrect, please try again.");
112 }
113 }
114 if(!success)
115 {
116 NSLog(@"Document authentication error....");
117 ret = 1;
118 return ret;
119 }
120
121 PTSecurityHandler *hdlr = [doc GetSecurityHandler];
122 NSLog(@"Document Open Password: %d", [hdlr IsUserPasswordRequired]);
123 NSLog(@"Permissions Password: %d", [hdlr IsMasterPasswordRequired]);
124 NSLog(@"Permissions: ");
125 NSLog(@" Has 'owner' permissions: %d", [hdlr GetPermission: e_ptowner]);
126 NSLog(@" Open and decrypt the document: %d", [hdlr GetPermission: e_ptdoc_open]);
127 NSLog(@" Allow content extraction: %d", [hdlr GetPermission: e_ptextract_content]);
128 NSLog(@" Allow full document editing: %d", [hdlr GetPermission: e_ptdoc_modify]);
129 NSLog(@" Allow printing: %d", [hdlr GetPermission: e_ptprint]);
130 NSLog(@" Allow high resolution printing: %d", [hdlr GetPermission: e_ptprint_high]);
131 NSLog(@" Allow annotation editing: %d", [hdlr GetPermission: e_ptmod_annot]);
132 NSLog(@" Allow form fill: %d", [hdlr GetPermission: e_ptfill_forms]);
133 NSLog(@" Allow content extraction for accessibility: %d", [hdlr GetPermission: e_ptaccess_support]);
134 NSLog(@" Allow document assembly: %d", [hdlr GetPermission: e_ptassemble_doc]);
135 }
136
137 //remove all security on the document
138 [doc RemoveSecurity];
139 [doc SaveToFile: @"../../TestFiles/Output/not_secured.pdf" flags: 0];
140
141 }
142 @catch(NSException *e)
143 {
144 NSLog(@"%@", e.reason);
145 ret = 1;
146 }
147
148 // Example 3:
149 // Encrypt/Decrypt a PDF using PDFTron custom security handler
150
151 @try
152 {
153 NSLog(@"-------------------------------------------------");
154 NSLog(@"Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
155 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/BusinessCardTemplate.pdf"];
156
157 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
158 unsigned int custom_id = 123456789;
159 PTSecurityHandler* custom_handler = [[PTPDFTronCustomSecurityHandler alloc] initWithCustom_id : custom_id];
160
161 // Add a password to the custom security handler
162 NSString *pass = @"test";
163 [custom_handler ChangeUserPassword: pass];
164
165 [doc SetSecurityHandler: custom_handler];
166
167 // Save the changes.
168 [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf" flags: 0];
169
170
171 NSLog(@"Decrypt the PDFTron custom security encrypted document above...");
172 // Register the PDFTron Custom Security handler with the same custom id used in encryption
173 [PTPDFNet AddPDFTronCustomHandler : custom_id];
174 PTPDFDoc *doc_enc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf"];
175 [doc_enc InitStdSecurityHandler : pass];
176 [doc RemoveSecurity];
177 // Save the decrypted document
178 [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc_dec.pdf" flags: 0];
179 NSLog(@"Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
180
181 }
182 @catch(NSException *e)
183 {
184 NSLog(@"%@", e.reason);
185 ret = 1;
186 }
187 [PTPDFNet Terminate: 0];
188 return ret;
189 }
190}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales