-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasswdmgr-documented.py
More file actions
209 lines (198 loc) · 9.88 KB
/
Copy pathpasswdmgr-documented.py
File metadata and controls
209 lines (198 loc) · 9.88 KB
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
208
209
import customtkinter as ctk
from tkinter import messagebox
import os.path
from cryptography.fernet import Fernet
from argon2 import PasswordHasher
import json
import pyperclip
class Root(ctk.CTk):
"""
main window of the password manager:
Initializes GUI, takes care of login, password storage and encryption
"""
def __init__(self):
super().__init__()
self.title('Password Manager')
self.window_width = 540
self.window_height = 440
self.screen_width = self.winfo_screenwidth()
self.screen_height = self.winfo_screenheight()
self.x = (self.screen_width / 2) - (self.window_width / 2)
self.y = (self.screen_height / 2) - (self.window_height / 2)
self.geometry(f'{self.window_width}x{self.window_height}+{int(self.x)}+{int(self.y)}')
self.master_input = ctk.StringVar()
self.ph = PasswordHasher()
self.checkForMaster()
self.json_path = 'passwords.json'
def loadJson(self):
if os.path.exists(self.json_path) and os.path.getsize(self.json_path) > 0:
with open(self.json_path, 'r') as file:
self.passwd_data = json.load(file)
else:
self.passwd_data = []
def savingPasswd(self):
"""
saves a new password entry to the JSON storage
"""
self.loadJson()
passwd = self.passwd_entry.get()
passwd_name = self.passwd_name_entry.get()
f = self.checkOrCreateKeyFile()
encryptedPasswd = f.encrypt(passwd.encode())
encryptedPasswd = encryptedPasswd.decode()
new_entry = {
"name": passwd_name,
"password": encryptedPasswd
}
self.passwd_data.append(new_entry)
with open(self.json_path, 'w') as file:
json.dump(self.passwd_data, file)
messagebox.showinfo(' ', 'Saving password was successful...')
for widget in self.passwords_frame.winfo_children():
widget.destroy()
self.addPasswdToFrame()
def deletingPasswd(self, entry):
"""
deletes a specified password entry from the stored data
"""
self.loadJson()
if entry in self.passwd_data:
self.passwd_data.remove(entry)
with open(self.json_path, 'w') as file:
json.dump(self.passwd_data, file)
messagebox.showinfo(' ', 'Removing password was successful...')
for widget in self.passwords_frame.winfo_children():
widget.destroy()
self.addPasswdToFrame()
else:
messagebox.showinfo(' ', 'ERROR: Password does not exist')
def userInterface(self):
"""
creates the main user interfadce of the password manager
"""
self.title_label = ctk.CTkLabel(self, text='your passwords:', font=('Calibri', 30, 'bold'))
self.title_label.grid(row=0, column=0, padx=(3, 20), sticky='nsew')
self.passwords_frame = ctk.CTkScrollableFrame(self, orientation='vertical', width=250)
self.passwords_frame.grid(row=1, column=0, padx=(4, 20), pady=(0, 20), sticky='nsew')#, padx=20, pady=20, sticky="nsew"
self.form_frame = ctk.CTkFrame(self, fg_color='transparent')
self.form_frame.grid(row=1, column=1, sticky='nsew', pady=(0, 5))
self.passwd_name_entry = ctk.CTkEntry(self.form_frame, placeholder_text='name') #entry password name
self.passwd_name_entry.grid(row=1, column=1, pady=(0, 5), sticky='nsew') #pady(abstand oben, unten)
self.passwd_entry = ctk.CTkEntry(self.form_frame, placeholder_text='password', show='*') #entry password
self.passwd_entry.grid(row=2, column=1, pady=(0, 5), sticky='nsew')
self.password_button = ctk.CTkButton(self.form_frame, text='add', command = self.savingPasswd)
self.password_button.grid(row=3, column=1, pady=(0, 5))
self.addPasswdToFrame()
def addPasswdToFrame(self):
"""
displays all stored passwords from the JSON file in the GUI:
1. decrypts each password using the Fernetb key
2. creates a label for each password entry showing name and decrypted value
"""
self.loadJson()
f = self.checkOrCreateKeyFile()
for entry in self.passwd_data:
try:
decryptedPasswd = f.decrypt(entry['password'].encode()).decode() #encode(): base64 string--> bytes decode(): wieder zu string
passwd_label = ctk.CTkLabel(self.passwords_frame, text_color='white' ,text=f'{entry['name']}: {decryptedPasswd}') #: {decryptedPasswd}
passwd_label.pack(pady=2, anchor='w')
text = f'{entry['name']}: {decryptedPasswd}'
passwd_label.bind('<Button-1>', lambda event, t=text: pyperclip.copy(t))
passwd_label.bind("<Leave>", lambda event, lbl=passwd_label: lbl.configure(text_color="white"))
passwd_label.bind("<Enter>", lambda event, lbl=passwd_label: lbl.configure(text_color="lightblue")) #"lightblue" passwd_label.configure(text_color="red")
delete_passwd_button = ctk.CTkButton(self.passwords_frame, text='Delete', command=lambda e=entry: self.deletingPasswd(e))
delete_passwd_button.pack(pady=2, anchor='w')
except Exception as e:
passwd_label = ctk.CTkLabel(self.passwords_frame, text_color='white' ,text=f'{entry['name']}: [DECRYPTION ERROR]')
passwd_label.pack(pady=2, anchor='w')
def createMaster(self):
"""
Only called if no master password exists
1. displays an input form where the user can define a secure master password
2. if submit: hashing password using Argon2 and save it to 'master.txt'
3. loading main password manager interface
"""
def saving():
hash = self.ph.hash(self.master_input.get())
with open('master.txt', 'w') as file:
file.write(hash)
msg=messagebox.showinfo(' ', 'Master-Password was saved successfully!')
for widgets in self.winfo_children():
widgets.destroy()
self.userInterface()
self.master_frame = ctk.CTkFrame(self, corner_radius=10)
self.master_frame.pack(pady=40,padx=60,fill='both',expand=True)
self.master_label = ctk.CTkLabel(self.master_frame, text='Please specify your Master-Password.', font=('Calibri', 14, 'bold'))
self.master_label.place(relx=0.5, rely=0.3, anchor='center')
self.master_entry = ctk.CTkEntry(self.master_frame, textvariable=self.master_input, show='*')
self.master_entry.place(relx=0.5, rely=0.4, anchor = 'center')
self.master_submit_button = ctk.CTkButton(self.master_frame, text='Submit', command = saving, corner_radius=32,
fg_color='#8a5df4',hover_color='#8e6cc4')
self.master_submit_button.place(relx=0.5, rely=0.5, anchor = 'center')
def login(self):
"""
1. attemps to read the stored Argon2 hash from 'master.txt'
2. verifies the users input against the hash
3. if valid: loads the main password manager interface
if invalid or file missing: shows an error message
"""
def check():
try:
with open('master.txt', 'r') as file:
hash = file.read()
except:
msg = messagebox.showinfo('Error', 'Master file not found!')
return
try:
if self.ph.verify(hash, self.master_input.get()):
for widgets in self.winfo_children():
widgets.destroy()
self.userInterface()
else:
print('no')
msg=messagebox.showinfo(' ', 'Invalid Master-Password! Please try again!')
except Exception as e:
msg = messagebox.showinfo(' ', f'Error: {e}')
self.login_frame=ctk.CTkFrame(self,corner_radius=10)
self.login_frame.pack(pady=40,padx=60,fill='both',expand=True)
self.login_label=ctk.CTkLabel(self.login_frame, text='Master Password', font=('Calibri', 16, 'bold'))
self.login_label.place(relx=0.5,rely=0.3,anchor='center')
self.login_entry = ctk.CTkEntry(self.login_frame,textvariable=self.master_input,show='*')
self.login_entry.place(relx=0.5,rely=0.4,anchor='center')
self.login_button = ctk.CTkButton(self.login_frame,text='Submit',command=check,corner_radius=32,
fg_color='#8a5df4',hover_color='#8e6cc4')
self.login_button.place(relx=0.5,rely=0.5,anchor='center')
def checkForMaster(self):
"""
checks whether a master password already exists
if yes: display login
if not: prompt to create a new master password
"""
master_path = 'master.txt'
if os.path.exists(master_path):
self.login()
else:
self.createMaster()
def checkOrCreateKeyFile(self):
"""
if key file exists: reads and returns the key
if not: creates a new Fernet key, saves it, and returns it
"""
key_path='PassKey.key'
if os.path.exists(key_path):
with open(key_path, 'rb') as file:
key = file.read()
else:
msg=messagebox.showinfo(' ', 'Cant find key. Generating new...')
key = Fernet.generate_key()
with open(key_path, 'wb') as file:
file.write(key)
return Fernet(key)
if __name__ =='__main__':
root = Root()
ctk.set_appearance_mode('dark')
ctk.set_default_color_theme("blue")
ctk.set_widget_scaling(2.5)
ctk.set_window_scaling(2.2)
root.resizable(False, False)
root.mainloop()