Encryption

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

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6package com.pdftron.android.pdfnetsdksamples.samples;
7
8import com.pdftron.android.pdfnetsdksamples.OutputListener;
9import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
10import com.pdftron.android.pdfnetsdksamples.R;
11import com.pdftron.android.pdfnetsdksamples.util.Utils;
12import com.pdftron.common.PDFNetException;
13import com.pdftron.filters.FilterReader;
14import com.pdftron.filters.FlateEncode;
15import com.pdftron.filters.MappedFile;
16import com.pdftron.pdf.PDFDoc;
17import com.pdftron.pdf.PDFNet;
18import com.pdftron.sdf.Obj;
19import com.pdftron.sdf.PDFTronCustomSecurityHandler;
20import com.pdftron.sdf.SDFDoc;
21import com.pdftron.sdf.SecurityHandler;
22
23import java.io.BufferedReader;
24import java.io.InputStreamReader;
25import java.util.ArrayList;
26
27public class EncTest extends PDFNetSample {
28
29 private static OutputListener mOutputListener;
30
31 private static ArrayList<String> mFileList = new ArrayList<>();
32
33 public EncTest() {
34 setTitle(R.string.sample_encryption_title);
35 setDescription(R.string.sample_encryption_description);
36 }
37
38 @Override
39 public void run(OutputListener outputListener) {
40 super.run(outputListener);
41 mOutputListener = outputListener;
42 mFileList.clear();
43 printHeader(outputListener);
44
45 // Example 1:
46 // secure a document with password protection and
47 // adjust permissions
48
49 // Open the test file
50 mOutputListener.println("Securing an existing document ...");
51 try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "fish.pdf").getAbsolutePath()))) {
52 doc.initSecurityHandler();
53
54 // Perform some operation on the document. In this case we use low level SDF API
55 // to replace the content stream of the first page with contents of file 'my_stream.txt'
56 if (true) // Optional
57 {
58 mOutputListener.println("Replacing the content stream, use flate compression...");
59
60 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
61 Obj page_dict = doc.getTrailer().get("Root").value()
62 .get("Pages").value()
63 .get("Kids").value()
64 .getAt(0);
65
66 // Embed a custom stream (file mystream.txt) using Flate compression.
67 MappedFile embed_file = new MappedFile((Utils.getAssetTempFile(INPUT_PATH + "my_stream.txt").getAbsolutePath()));
68 FilterReader mystm = new FilterReader(embed_file);
69 page_dict.put("Contents",
70 doc.createIndirectStream(mystm,
71 new FlateEncode(null)));
72 }
73
74 //encrypt the document
75
76 // Apply a new security handler with given security settings.
77 // In order to open saved PDF you will need a user password 'test'.
78 SecurityHandler new_handler = new SecurityHandler();
79
80 // Set a new password required to open a document
81 String user_password = "test";
82 new_handler.changeUserPassword(user_password);
83
84 // Set Permissions
85 new_handler.setPermission(SecurityHandler.e_print, true);
86 new_handler.setPermission(SecurityHandler.e_extract_content, false);
87
88 // Note: document takes the ownership of new_handler.
89 doc.setSecurityHandler(new_handler);
90
91 // Save the changes.
92 mOutputListener.println("Saving modified file...");
93 doc.save((Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath()), SDFDoc.SaveMode.NO_FLAGS, null);
94 } catch (PDFNetException e) {
95 mOutputListener.printError(e.getStackTrace());
96 }
97
98 // Example 2:
99 // Opens the encrypted document and removes all of
100 // its security.
101 try (PDFDoc doc = new PDFDoc((Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath()))) {
102 //If the document is encrypted prompt for the password
103 if (!doc.initSecurityHandler()) {
104 boolean success = false;
105 mOutputListener.println("The password is: test");
106 for (int count = 0; count < 3; count++) {
107 BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
108 mOutputListener.println("A password required to open the document.");
109 mOutputListener.print("Please enter the password: ");
110 // String password = r.readLine();
111 if (doc.initStdSecurityHandler("test")) {
112 success = true;
113 mOutputListener.println("The password is correct.");
114 break;
115 } else if (count < 3) {
116 mOutputListener.println("The password is incorrect, please try again");
117 }
118 }
119 if (!success) {
120 mOutputListener.println("Document authentication error....");
121 }
122 }
123
124 //remove all security on the document
125 doc.removeSecurity();
126 doc.save(Utils.createExternalFile("not_secured.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
127 } catch (Exception e) {
128 mOutputListener.printError(e.getStackTrace());
129 }
130
131 // Example 3:
132 // Encrypt/Decrypt a PDF using PDFTron custom security handler
133 mOutputListener.println("-------------------------------------------------");
134 mOutputListener.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
135 try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "BusinessCardTemplate.pdf").getAbsolutePath()))
136 {
137 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
138 int custom_id = 123456789;
139 PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
140
141 // Add a password to the custom security handler
142 String pass = "test";
143 custom_handler.changeUserPassword(pass);
144
145 // Save the encrypted document
146 doc.setSecurityHandler(custom_handler);
147 doc.save(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
148
149 mOutputListener.println("Decrypt the PDFTron custom security encrypted document above...");
150 // Register the PDFTron Custom Security handler with the same custom id used in encryption
151 PDFNet.addPDFTronCustomHandler(custom_id);
152
153 PDFDoc doc_enc = new PDFDoc(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath());
154 doc_enc.initStdSecurityHandler(pass);
155 doc_enc.removeSecurity();
156 // Save the decrypted document
157 doc_enc.save(Utils.createExternalFile("BusinessCardTemplate_enc_dec.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
158 mOutputListener.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
159 } catch (Exception e) {
160 mOutputListener.printError(e.getStackTrace());
161 }
162 mOutputListener.println("-------------------------------------------------");
163 mOutputListener.println("Tests completed.");
164
165 for (String file : mFileList) {
166 addToFileList(file);
167 }
168 printFooter(outputListener);
169 }
170
171}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales