-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadder.py
More file actions
216 lines (178 loc) · 7.24 KB
/
Copy pathadder.py
File metadata and controls
216 lines (178 loc) · 7.24 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
210
211
212
213
214
215
216
#!/usr/bin/env python3
import sys
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import getpass
from fuzzywuzzy import process
BACKEND = default_backend()
SALT_SIZE = 16 # 128-bit salt
KEY_SIZE = 32 # 256-bit key
NONCE_SIZE = 12 # 96-bit nonce
TAG_SIZE = 16
ITERATIONS = 100000
FILE_PATH = "/path/to/file"
def write_to_file(text):
with open(FILE_PATH, 'a') as file:
file.write(f"{text}\n")
def secure_delete(file_path, passes=3):
"""Securely delete a file by overwriting it with random data multiple times."""
with open(file_path, 'ba+', buffering=0) as f:
length = f.tell()
for _ in range(passes):
f.seek(0)
f.write(os.urandom(length))
os.remove(file_path)
def delete_from_file(line_num):
with open(FILE_PATH, 'r') as file:
lines = file.readlines()
with open(FILE_PATH, 'w') as file:
for index, line in enumerate(lines):
if index != line_num:
file.write(line)
def find_closest_string(target, string_list):
closest_match = process.extractOne(target, string_list)
return closest_match[0]
def get_file_name(file_path):
# Finds the position of the last '/'
position_index = file_path.rfind('/')
# If '/' is not found, return the whole string
if position_index == -1:
return file_path
# Extract substring from the end to the first '/' (excluding) found
return file_path[position_index + 1:]
class Encryptor:
@staticmethod
def generate_key(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=KEY_SIZE,
salt=salt,
iterations=ITERATIONS,
backend=BACKEND
)
return kdf.derive(password.encode())
@staticmethod
def encrypt_file(file_path, password):
"""Encrypt the file and save it with .enc extension."""
salt = os.urandom(SALT_SIZE)
key = Encryptor.generate_key(password, salt)
nonce = os.urandom(NONCE_SIZE)
cipher = Cipher(
algorithms.AES(key),
modes.GCM(nonce),
backend=BACKEND
)
encryptor = cipher.encryptor()
with open(file_path, 'rb') as f:
plaintext = f.read()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
with open(file_path + '.enc', 'wb') as f:
f.write(salt + nonce + encryptor.tag + ciphertext)
secure_delete(file_path)
print(f"File {FILENAME} encrypted successfully and plaintext deleted.")
@staticmethod
def decrypt_file(file_path, password):
"""Decrypt the file and save the result without .enc extension."""
with open(file_path, 'rb') as f:
salt = f.read(SALT_SIZE)
nonce = f.read(NONCE_SIZE)
tag = f.read(TAG_SIZE)
ciphertext = f.read()
key = Encryptor.generate_key(password, salt)
cipher = Cipher(
algorithms.AES(key),
modes.GCM(nonce, tag),
backend=BACKEND
)
decryptor = cipher.decryptor()
try:
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
except Exception as e:
print(f"Decryption failed: {e}")
raise Exception
with open(file_path.replace('.enc', ''), 'wb') as f:
f.write(plaintext)
print(f"File {FILENAME} decrypted successfully.")
return True
def get_master_pass():
while True:
password = getpass.getpass(prompt="Set your master password (main password to decrypt text file):")
confirm_password = getpass.getpass(prompt="Confirm your master password:")
if password == confirm_password:
return password
else:
print("Password and confirmed password are not the same")
def auth_decrypt():
"""Decrypts the file after the correct password is entered otherwise terminates the program"""
count = 0
valid = False
### Checks if file passwords file doesnt exist at all
if not os.path.isfile(FILE_PATH) and not os.path.isfile(FILE_PATH+'.enc'):
print(f"{FILENAME} file not found >>>\nCreating a {FILENAME} file for you...")
with open(FILE_PATH, 'w') as f:
pass
password = get_master_pass()
Encryptor.encrypt_file(FILE_PATH, password)
### Checks if you have an unencrypted file
elif os.path.isfile(FILE_PATH):
print(f"Found an unencrypted {FILENAME} text file storing the passwords!")
password = get_master_pass()
Encryptor.encrypt_file(FILE_PATH, password)
print(f"===Successfully recovered {FILENAME} file and encrypted it===")
while count < 3 and valid == False:
password = getpass.getpass(prompt='Enter password to open encrypted file: ')
try:
valid = Encryptor.decrypt_file(FILE_PATH+'.enc', password)
except Exception as e:
print(f"Incorrect password: {e}")
count += 1
if count == 3:
quit()
return password
def file_reader(file_path):
with open(file_path, "r") as file:
#Read all the lines from the file
lines = [line.strip() for line in file]
return lines
def text_parser(lines):
string_list = lines
before_comma = [s.split(',')[0].strip() for s in string_list]
after_comma = [s.split(',', 1)[1].strip() for s in string_list]
return before_comma, after_comma
def menu():
choice = int(input("1). Add account \n2). Delete account\n3). Save changes\n:"))
if choice == 1:
account = input("Enter the account and/or a hint:")
password = getpass.getpass(prompt='Enter password: ')
write_to_file(f"{account}, {password}")
print(f">>>{account} has been written to the file")
return False
elif choice == 2:
lines = file_reader(FILE_PATH)
before_comma, _ = text_parser(lines)
print(before_comma)
account = input("Enter account to delete:")
if account == "!q" or account == "q!":
return True
closest = find_closest_string(account, before_comma)
line_num = before_comma.index(closest)
delete_from_file(line_num)
print(f"{closest} account deleted...")
return False
elif choice == 3:
return True
else:
return False
if __name__ == "__main__":
FILENAME = get_file_name(FILE_PATH)
print('IF YOU WANT TO ADD PASSWORDS QUICKLY \n1).CREATE A "Passwords.txt" file or just "Passwords" (on windows)\n2).Insert passwords in the format "label,password" (no spaces) and seperate each entry with a new line\n3).Open either Adder or Crimson\nOr simply just use the adder program and add them 1 by 1\nTIP - Make sure adder and crimson are in the same folder preferably a designated passwords folder')
print("\n"*3+"Resuming program...")
encryptor = Encryptor()
master_pass = auth_decrypt()
valid = False
while valid == False:
valid = menu()
encryptor.encrypt_file(FILE_PATH, master_pass)