-
Notifications
You must be signed in to change notification settings - Fork 1
/
password_vault.py
387 lines (293 loc) · 10.8 KB
/
password_vault.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import sqlite3, hashlib
from tkinter import *
from tkinter import simpledialog
from functools import partial
import uuid
import pyperclip
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.fernet import Fernet
import secrets
import string
# MAKE A KEY WHICH IS RANDOMLY GENERATED AND WILL BE USED TO ENCRYPT USER DATA
# STORE THAT KEY ENCRYPTED BY THE USER PASSWORD HASH OR RECOVERY KEY HASH
# THAT KEY CAN THAN BE RECOVERED IN BOTH MANNERS
backend = default_backend()
salt = b"2444"
def kdf():
return PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=backend)
encryptionKey = 0
def encrypt(message: bytes, key: bytes) -> bytes:
return Fernet(key).encrypt(message)
def decrypt(message: bytes, token: bytes) -> bytes:
return Fernet(token).decrypt(message)
def genPassword(length: int) -> str:
return "".join(
(
secrets.choice(string.ascii_letters + string.digits + string.punctuation)
for i in range(length)
)
)
# database code
with sqlite3.connect("password_vault.db") as db:
cursor = db.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS masterpassword(
id INTEGER PRIMARY KEY,
password TEXT NOT NULL,
recoveryKey TEXT NOT NULL);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS vault(
id INTEGER PRIMARY KEY,
website TEXT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS masterkey(
id INTEGER PRIMARY KEY,
masterKeyPassword TEXT NOT NULL,
masterKeyRecoveryKey TEXT NOT NULL);
"""
)
# Create PopUp
def popUp(text):
answer = simpledialog.askstring("input string", text)
return answer
# Initiate window
window = Tk()
window.update()
window.title("Password Vault")
def hashPassword(input):
hash1 = hashlib.sha256(input)
hash1 = hash1.hexdigest()
return hash1
def firstTimeScreen(hasMasterKey=None):
for widget in window.winfo_children():
widget.destroy()
window.geometry("250x125")
lbl = Label(window, text="Choose a Master Password")
lbl.config(anchor=CENTER)
lbl.pack()
txt = Entry(window, width=20, show="*")
txt.pack()
txt.focus()
lbl1 = Label(window, text="Re-enter password")
lbl1.config(anchor=CENTER)
lbl1.pack()
txt1 = Entry(window, width=20, show="*")
txt1.pack()
def savePassword():
if txt.get() == txt1.get():
sql = "DELETE FROM masterpassword WHERE id = 1"
cursor.execute(sql)
hashedPassword = hashPassword(txt.get().encode())
key = str(uuid.uuid4().hex)
hashedRecoveryKey = hashPassword(key.encode())
insert_password = """INSERT INTO masterpassword(password, recoveryKey)
VALUES(?, ?) """
cursor.execute(insert_password, ((hashedPassword), (hashedRecoveryKey)))
# Check if masterkey exists, if it does replace it by encrypting it with new password hash, and new recoverykey hash
# if it does not, generate a masterkey and encrypt it with new password hash, and new recoverykey hash
masterKey = hasMasterKey if hasMasterKey else genPassword(64)
cursor.execute("SELECT * FROM masterkey")
if cursor.fetchall():
cursor.execute("DELETE FROM masterkey WHERE id = 1")
insert_masterkey = """INSERT INTO masterkey(masterKeyPassword, masterKeyRecoveryKey)
VALUES(?, ?) """
cursor.execute(
insert_masterkey,
(
(encrypt(masterKey.encode(), base64.urlsafe_b64encode(kdf().derive(txt.get().encode())))),
(encrypt(masterKey.encode(), base64.urlsafe_b64encode(kdf().derive(key.encode())))),
),
)
# change encryptionKey to masterKey unencrypted by masterpassword
global encryptionKey
encryptionKey = base64.urlsafe_b64encode(kdf().derive(masterKey.encode()))
db.commit()
recoveryScreen(key)
else:
lbl.config(text="Passwords dont match")
btn = Button(window, text="Save", command=savePassword)
btn.pack(pady=5)
def recoveryScreen(key):
for widget in window.winfo_children():
widget.destroy()
window.geometry("250x125")
lbl = Label(window, text="Save this key to be able to recover account")
lbl.config(anchor=CENTER)
lbl.pack()
lbl1 = Label(window, text=key)
lbl1.config(anchor=CENTER)
lbl1.pack()
def copyKey():
pyperclip.copy(lbl1.cget("text"))
btn = Button(window, text="Copy Key", command=copyKey)
btn.pack(pady=5)
def done():
vaultScreen()
btn = Button(window, text="Done", command=done)
btn.pack(pady=5)
def resetScreen():
for widget in window.winfo_children():
widget.destroy()
window.geometry("250x125")
lbl = Label(window, text="Enter Recovery Key")
lbl.config(anchor=CENTER)
lbl.pack()
txt = Entry(window, width=20)
txt.pack()
txt.focus()
lbl1 = Label(window)
lbl1.config(anchor=CENTER)
lbl1.pack()
def getRecoveryKey():
recoveryKeyCheck = hashPassword(str(txt.get()).encode())
cursor.execute(
"SELECT * FROM masterpassword WHERE id = 1 AND recoveryKey = ?",
[(recoveryKeyCheck)],
)
return cursor.fetchall()
def checkRecoveryKey():
recoveryKey = getRecoveryKey()
if recoveryKey:
# unencrypt masterKey and pass it to firstTimeScreen
cursor.execute("SELECT * FROM masterkey")
masterKeyEntry = cursor.fetchall()
if masterKeyEntry:
masterKeyRecoveryKey = masterKeyEntry[0][2]
masterKey = decrypt(masterKeyRecoveryKey, base64.urlsafe_b64encode(kdf().derive(str(txt.get()).encode()))).decode()
firstTimeScreen(masterKey)
else:
print("Master Key entry missing!")
exit()
else:
txt.delete(0, "end")
lbl1.config(text="Wrong Key")
btn = Button(window, text="Check Key", command=checkRecoveryKey)
btn.pack(pady=5)
def loginScreen():
for widget in window.winfo_children():
widget.destroy()
window.geometry("250x125")
lbl = Label(window, text="Enter Master Password")
lbl.config(anchor=CENTER)
lbl.pack()
txt = Entry(window, width=20, show="*")
txt.pack()
txt.focus()
lbl1 = Label(window)
lbl1.config(anchor=CENTER)
lbl1.pack(side=TOP)
def getMasterPassword():
checkHashedPassword = hashPassword(txt.get().encode())
cursor.execute(
"SELECT * FROM masterpassword WHERE id = 1 AND password = ?",
[(checkHashedPassword)],
)
return cursor.fetchall()
def checkPassword():
password = getMasterPassword()
if password:
# change encryptionKey to masterKey unencrypted by masterpassword
cursor.execute("SELECT * FROM masterkey")
masterKeyEntry = cursor.fetchall()
if masterKeyEntry:
masterKeyPassword = masterKeyEntry[0][1]
print(txt.get().encode())
masterKey = decrypt(masterKeyPassword, base64.urlsafe_b64encode(kdf().derive(txt.get().encode())))
global encryptionKey
encryptionKey = base64.urlsafe_b64encode(kdf().derive(masterKey))
vaultScreen()
else:
print("Master Key entry missing!")
exit()
else:
txt.delete(0, "end")
lbl1.config(text="Wrong Password")
def resetPassword():
resetScreen()
btn = Button(window, text="Submit", command=checkPassword)
btn.pack(pady=5)
btn = Button(window, text="Reset Password", command=resetPassword)
btn.pack(pady=5)
def vaultScreen():
for widget in window.winfo_children():
widget.destroy()
def addEntry():
text1 = "Website"
text2 = "Username"
text3 = "Password"
website = encrypt(popUp(text1).encode(), encryptionKey)
username = encrypt(popUp(text2).encode(), encryptionKey)
password = encrypt(popUp(text3).encode(), encryptionKey)
insert_fields = """INSERT INTO vault(website, username, password)
VALUES(?, ?, ?) """
cursor.execute(insert_fields, (website, username, password))
db.commit()
vaultScreen()
def removeEntry(input):
cursor.execute("DELETE FROM vault WHERE id = ?", (input,))
db.commit()
vaultScreen()
window.geometry("750x550")
window.resizable(height=None, width=None)
lbl = Label(window, text="Password Vault")
lbl.grid(column=1)
btn = Button(window, text="+", command=addEntry)
btn.grid(column=1, pady=10)
lbl = Label(window, text="Website")
lbl.grid(row=2, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=2, column=1, padx=80)
lbl = Label(window, text="Password")
lbl.grid(row=2, column=2, padx=80)
cursor.execute("SELECT * FROM vault")
if cursor.fetchall() != None:
i = 0
while True:
cursor.execute("SELECT * FROM vault")
array = cursor.fetchall()
if len(array) == 0:
break
lbl1 = Label(
window,
text=(decrypt(array[i][1], encryptionKey)),
font=("Helvetica", 12),
)
lbl1.grid(column=0, row=(i + 3))
lbl2 = Label(
window,
text=(decrypt(array[i][2], encryptionKey)),
font=("Helvetica", 12),
)
lbl2.grid(column=1, row=(i + 3))
lbl3 = Label(
window,
text=(decrypt(array[i][3], encryptionKey)),
font=("Helvetica", 12),
)
lbl3.grid(column=2, row=(i + 3))
btn = Button(
window, text="Delete", command=partial(removeEntry, array[i][0])
)
btn.grid(column=3, row=(i + 3), pady=10)
i = i + 1
cursor.execute("SELECT * FROM vault")
if len(cursor.fetchall()) <= i:
break
cursor.execute("SELECT * FROM masterpassword")
if cursor.fetchall():
loginScreen()
else:
firstTimeScreen()
window.mainloop()