Encryption

Sample C# code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our Server SDK.

1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4
5using System;
6using pdftron;
7using pdftron.Common;
8using pdftron.Filters;
9using pdftron.SDF;
10using pdftron.PDF;
11
12namespace EncTestCS
13{
14 // A custom security handler used to obtain document password dynamically via user feedback.
15 class MySecurityHandler : StdSecurityHandler
16 {
17 public MySecurityHandler (Int32 key_len, Int32 enc_code) : base(key_len, enc_code) {}
18 public MySecurityHandler (MySecurityHandler s) : base(s) {}
19
20 // In this callback ask the user for password/authorization data.
21 // This may involve a dialog box used to collect authorization data or something else.
22 override public bool GetAuthorizationData (SecurityHandler.Permission p)
23 {
24 Console.WriteLine("The input file requires user password.");
25 Console.WriteLine("Please enter the password:");
26 String pass = Console.ReadLine();
27 InitPassword(pass);
28 return true;
29 }
30
31 // This callback could be used to customize security handler preferences.
32 override public bool EditSecurityData(SDFDoc doc) { return false; }
33
34 // This callback is used when authorization process fails.
35 override public void AuthorizeFailed()
36 {
37 Console.WriteLine("Authorize failed...");
38 }
39
40 public static SecurityHandler Create(String name, Int32 key_len, Int32 enc_code) { return new MySecurityHandler(key_len, enc_code); }
41
42 override public SecurityHandler Clone() { return new MySecurityHandler(this); }
43 }
44
45 /// <summary>
46 //---------------------------------------------------------------------------------------
47 // This sample shows encryption support in PDFNet. The sample reads an encrypted document and
48 // sets a new SecurityHandler. The sample also illustrates how password protection can
49 // be removed from an existing PDF document.
50 //---------------------------------------------------------------------------------------
51 /// </summary>
52 class Class1
53 {
54 private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
55 static Class1() {}
56
57 static void Main(string[] args)
58 {
59 PDFNet.Initialize(PDFTronLicense.Key);
60
61 // Relative path to the folder containing test files.
62 string input_path = "../../../../TestFiles/";
63 string output_path = "../../../../TestFiles/Output/";
64
65 // Example 1: Securing a document with password protection and adjusting permissions
66 // on the document.
67 try
68 {
69 // Open the test file
70 Console.WriteLine("-------------------------------------------------");
71 Console.WriteLine("Securing an existing document...");
72 using (PDFDoc doc = new PDFDoc(input_path + "fish.pdf"))
73 {
74
75 if (!doc.InitSecurityHandler())
76 {
77 Console.WriteLine("Document authentication error...");
78 return;
79 }
80
81 // Perform some operation on the document. In this case we use low level SDF API
82 // to replace the content stream of the first page with contents of file 'my_stream.txt'
83 if (true) // Optional
84 {
85 Console.WriteLine("Replacing the content stream, use flate compression...");
86
87 // Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0
88 Obj page_dict = doc.GetTrailer().Get("Root").Value().
89 Get("Pages").Value().Get("Kids").Value().GetAt(0);
90
91 // Embed a custom stream (file mystream.txt) using Flate compression.
92 MappedFile embed_file = new MappedFile(input_path + "my_stream.txt");
93 FilterReader mystm = new FilterReader(embed_file);
94 page_dict.Put("Contents", doc.CreateIndirectStream(mystm));
95 embed_file.Close();
96 }
97
98 // Apply a new security handler with given security settings.
99 // In order to open saved PDF you will need a user password 'test'.
100 StdSecurityHandler new_handler = new StdSecurityHandler();
101
102 // Set a new password required to open a document
103 string my_password = "test";
104 new_handler.ChangeUserPassword(my_password);
105
106 // Set Permissions
107 new_handler.SetPermission (SecurityHandler.Permission.e_print, true);
108 new_handler.SetPermission (SecurityHandler.Permission.e_extract_content, false);
109
110 // Note: document takes the ownership of new_handler.
111 doc.SetSecurityHandler(new_handler);
112
113 // Save the changes.
114 Console.WriteLine("Saving modified file...");
115 doc.Save(output_path + "secured.pdf", 0);
116 }
117
118 Console.WriteLine("Done. Result saved in secured.pdf");
119 }
120 catch (PDFNetException e)
121 {
122 Console.WriteLine(e.Message);
123 }
124
125 // Example 2: Reading password protected document without user feedback.
126 try
127 {
128 // In this sample case we will open an encrypted document that
129 // requires a user password in order to access the content.
130 Console.WriteLine("-------------------------------------------------");
131 Console.WriteLine("Open the password protected document from the first example...");
132 using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example.
133 {
134
135 Console.WriteLine("Initializing security handler without any user interaction...");
136
137 // At this point MySecurityHandler callbacks will be invoked.
138 // MySecurityHandler.GetAuthorizationData() should collect the password and
139 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
140 if (!doc.InitStdSecurityHandler("test"))
141 {
142 Console.WriteLine("Document authentication error...");
143 Console.WriteLine("The password is not valid.");
144 return;
145 }
146 else
147 {
148 Console.WriteLine("The password is correct! Document can now be used for reading and editing");
149
150 // Remove the password security and save the changes to a new file.
151 doc.RemoveSecurity();
152 doc.Save(output_path + "secured_nomore1.pdf", 0);
153 Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
154 }
155
156 }
157 }
158 catch (PDFNetException e)
159 {
160 Console.WriteLine(e.Message);
161 }
162
163 // Example 3:
164 // Encrypt/Decrypt a PDF using PDFTron custom security handler
165 try
166 {
167 Console.WriteLine("-------------------------------------------------");
168 Console.WriteLine("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
169 PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf");
170
171 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
172 int custom_id = 123456789;
173 PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
174
175 // Add a password to the custom security handler
176 String pass = "test";
177 custom_handler.ChangeUserPassword(pass);
178
179 // Save the encrypted document
180 doc.SetSecurityHandler(custom_handler);
181 doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0);
182
183 Console.WriteLine("Decrypt the PDFTron custom security encrypted document above...");
184 // Register the PDFTron Custom Security handler with the same custom id used in encryption
185 PDFNet.AddPDFTronCustomHandler(custom_id);
186
187 PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
188 doc_enc.InitStdSecurityHandler(pass);
189 doc_enc.RemoveSecurity();
190 // Save the decrypted document
191 doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0);
192 Console.WriteLine("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
193 }
194 catch (PDFNetException e)
195 {
196 Console.WriteLine(e.Message);
197 }
198
199 // Example 4: Reading password protected document with user feedback.
200 try
201 {
202 // Register standard security. Reguired only once per application session.
203 CreateDelegate del = new CreateDelegate(MySecurityHandler.Create);
204 SecurityManagerSingleton.Instance().RegisterSecurityHandler("Standard",
205 new SecurityDescriptor("Standard Security", del));
206
207 Console.WriteLine("-------------------------------------------------");
208 Console.WriteLine("Open the password protected document from the first example...");
209 using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example.
210 {
211
212 Console.WriteLine("Initializing security handler. The password will now be collected from the user");
213 Console.WriteLine("Enter 'test' as the password.");
214
215 // At this point MySecurityHandler callbacks will be invoked.
216 // MySecurityHandler.GetAuthorizationData() should collect the password and
217 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
218 if (!doc.InitSecurityHandler())
219 {
220 Console.WriteLine("Document authentication error...");
221 Console.WriteLine("The password is not valid.");
222 return;
223 }
224 else
225 {
226 Console.WriteLine("The password is correct! Document can now be used for reading and editing");
227
228 // Remove the password security and save the changes to a new file.
229 doc.RemoveSecurity();
230 doc.Save(output_path + "secured_nomore2.pdf", 0);
231 Console.WriteLine("Done. Result saved in secured_nomore2.pdf");
232 }
233 }
234 }
235 catch (PDFNetException e)
236 {
237 Console.WriteLine(e.Message);
238 }
239 PDFNet.Terminate();
240 Console.WriteLine("-------------------------------------------------");
241 Console.WriteLine("Tests completed.");
242
243 }
244 }
245}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales