-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpwd-to-pdf.py
207 lines (163 loc) · 8.07 KB
/
pwd-to-pdf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import tkinter as tk
from tkinter import filedialog, messagebox
from os import listdir
from os.path import isfile, join
import string
import random
import datetime
import csv
import json
import PyPDF2
LOG_FILE = "pwd-to-pdf.log"
PASSWORD_FILE = "pwd-to-pdf.pwd"
DEFAULT_PASSWORD_FILE = "pwd-to-pdf.default"
PASSWORD_COMPLEXITY_FILE = "pwd-to-pdf.config"
ART = """
╱╱╱╱╱╱╱╱╱╱╭╮╱╱╱╭╮╱╱╱╱╱╱╱╱╱╱╱╱╭╮╭━╮
╱╱╱╱╱╱╱╱╱╱┃┃╱╱╭╯╰╮╱╱╱╱╱╱╱╱╱╱╱┃┃┃╭╯
╭━━┳╮╭╮╭┳━╯┃╱╱╰╮╭╋━━╮╱╱╱╭━━┳━╯┣╯╰╮
┃╭╮┃╰╯╰╯┃╭╮┃╭━━┫┃┃╭╮┃╭━━┫╭╮┃╭╮┣╮╭╯
┃╰╯┣╮╭╮╭┫╰╯┃╰━━┫╰┫╰╯┃╰━━┫╰╯┃╰╯┃┃┃
┃╭━╯╰╯╰╯╰━━╯╱╱╱╰━┻━━╯╱╱╱┃╭━┻━━╯╰╯
┃┃╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱┃┃
╰╯╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╰╯
"""
pdf_dir = ""
def encrypt_pdf(file, passwd):
try:
pdf_in_file = open(file, 'rb')
input_pdf = PyPDF2.PdfFileReader(pdf_in_file)
pages_no = input_pdf.numPages
output = PyPDF2.PdfFileWriter()
for i in range(pages_no):
input_pdf = PyPDF2.PdfFileReader(pdf_in_file)
output.addPage(input_pdf.getPage(i))
output.encrypt(passwd)
with open(f"{file[:len(file) - 4]}.protected.pwd-to-pdf.pdf", "wb") as outputStream:
output.write(outputStream)
pdf_in_file.close()
except Exception as e:
write_log(f"{Exception}. {str(e)} . Error with PDF encryption for file {file}.")
messagebox.showerror("Error!", f"{str(e)}. Error with PDF encryption for file {file}. See log for more info!")
def get_help():
text = "This app encrypts pdfs in the selected directory files with passwords.\n" \
"To begin, select the directory and click Go!\n" \
"\n" \
"Autogenerated passwords will be applied to the pdfs and saved in pwd-to-pdf.pwd\n" \
"This file will be in same directory as the pdfs\n" \
"The data will be in csv format, where first line is the header, as shown below\n" \
"\n" \
"file_name,password\n" \
"file1.pdf,password123\n" \
"file2.pdf,password567\n" \
"\n" \
"You may also provide a default file named pwd-to-pdf.default\n" \
"This file must have part-of-filename, password in csv format\n" \
"This default password will be used when file match is found.\n" \
"\n" \
"file_name_pattern,default\n" \
"John Doe,123456\n" \
"Eve Adams,987654\n" \
"\n" \
"You may also change the autogenerated password complexity in the file named pwd-to-pdf.config\n" \
"Finally, application information and errors will be written in pwd-to-pdf.log"
messagebox.showinfo("HELP!!", text)
def get_dir():
global pdf_dir
try:
pdf_dir = tk.filedialog.askdirectory()
write_log("Directory successfully selected")
except Exception as e:
write_log(f"{Exception}. {str(e)} . Error with directory selection!")
messagebox.showerror("Error!", f"{str(e)}. Error with directory selection! See log for more info!")
def go():
global pdf_dir
sure = messagebox.askyesno("Confirm", "Are you sure you want encrypt pdfs in this directory?")
if sure:
try:
# get list of pdf files ---------------------------------
pdf_files = [f
for f in listdir(pdf_dir)
if isfile(join(pdf_dir, f)) and f[len(f) - 4:] == ".pdf" and "protected.pwd-to-pdf" not in f
]
write_log(f"PDF file list generated : {pdf_files}")
# get default passwords ----------------------------------
default_file_pass = []
if isfile(join(pdf_dir, DEFAULT_PASSWORD_FILE)):
write_log("Default password list found!!")
with open(join(pdf_dir, DEFAULT_PASSWORD_FILE), "r") as pwd_file_def:
csv_reader = csv.reader(pwd_file_def)
i = 0
for row in csv_reader:
if i > 0:
default_file_pass.append((row[0], row[1]))
i += 1
# get password complexity ---------------------------------
if isfile(join(pdf_dir, PASSWORD_COMPLEXITY_FILE)):
password_complexity_info = json.load(open(join(pdf_dir, PASSWORD_COMPLEXITY_FILE)))
else:
password_complexity_info = {
"password_complexity": {
"letters": 3,
"numbers": 1,
"symbols": 0
}
}
json_data = json.dumps(password_complexity_info, indent=4)
with open(join(pdf_dir, PASSWORD_COMPLEXITY_FILE), "w") as json_file:
json_file.write(json_data)
# apply passwords to pdfs -----------------------------------
success_count = 0
with open(join(pdf_dir, PASSWORD_FILE), "w") as pwd_file:
pwd_file.writelines("file,password\n")
for pdf in pdf_files:
has_default_password = False
password_to_apply = ""
for item in default_file_pass:
if item[0].lower() in pdf.lower():
has_default_password = True
password_to_apply = item[1]
break
if not has_default_password:
password_to_apply = get_auto_pwd(
password_complexity_info["password_complexity"]["letters"],
password_complexity_info["password_complexity"]["numbers"],
password_complexity_info["password_complexity"]["symbols"]
)
encrypt_pdf(join(pdf_dir, pdf), password_to_apply)
pwd_file.writelines(f"{pdf},{password_to_apply}\n")
write_log(f"PDF file encrypted : {join(pdf_dir, pdf)}")
success_count += 1
messagebox.showinfo("Info!", f"{success_count} files processed! See log for more info!")
except Exception as e:
write_log(f"{Exception}. {str(e)} . An Error occurred during processing!")
messagebox.showerror("Error!", f"{str(e)}. See log for more info!")
def get_auto_pwd(letters=0, numbers=0, symbols=0):
password = []
for _ in range(0, letters):
password.append(random.choice(string.ascii_letters))
for _ in range(0, numbers):
password.append(random.choice(string.digits))
for _ in range(0, symbols):
password.append(random.choice(string.punctuation))
random.shuffle(password)
return "".join(password)
def write_log(text):
try:
with open(join(pdf_dir, LOG_FILE), "a") as log:
log.write(f"{str(datetime.datetime.now())} : {text}\n")
except Exception as e:
messagebox.showerror("Error writing log", (str(e)))
window = tk.Tk()
window.title("Add password to pdf")
window.config(padx=10, pady=10)
canvas = tk.Canvas(width=400, height=120, highlightthickness=0)
canvas.create_text(200, 60, text=ART)
canvas.grid(row=1, column=0, columnspan=3, padx=10, pady=10)
b_help = tk.Button(text="Help", command=get_help)
b_help.grid(row=0, column=0)
b_dir = tk.Button(text="Select Directory", command=get_dir)
b_dir.grid(row=0, column=1)
b_go = tk.Button(text="Go!", command=go)
b_go.grid(row=0, column=2)
window.mainloop()