Repository navigation
Expand file tree
/
Copy pathencrypt_decrypt.py
More file actions
105 lines (73 loc) · 2.39 KB
/
Copy pathencrypt_decrypt.py
File metadata and controls
105 lines (73 loc) · 2.39 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
import os
import sys
from cryptography.fernet import Fernet, InvalidToken
KEY_FILE = "secret.key"
def generate_key():
if os.path.exists(KEY_FILE):
return
key = Fernet.generate_key()
with open(KEY_FILE, "wb") as f:
f.write(key)
print(f"New key generated and saved to {KEY_FILE}")
def load_key():
if not os.path.exists(KEY_FILE):
print("No key found. Generating a new one...")
generate_key()
with open(KEY_FILE, "rb") as f:
return f.read()
def encrypt_file(input_path):
if not os.path.exists(input_path):
print(f"File not found: {input_path}")
return
key = load_key()
fernet = Fernet(key)
with open(input_path, "rb") as f:
data = f.read()
encrypted_data = fernet.encrypt(data)
output_path = input_path + ".enc"
with open(output_path, "wb") as f:
f.write(encrypted_data)
print(f"File encrypted successfully -> {output_path}")
def decrypt_file(input_path):
if not os.path.exists(input_path):
print(f"File not found: {input_path}")
return
key = load_key()
fernet = Fernet(key)
with open(input_path, "rb") as f:
encrypted_data = f.read()
try:
decrypted_data = fernet.decrypt(encrypted_data)
except InvalidToken:
print("Decryption failed. Invalid key or corrupted file.")
return
if input_path.endswith(".enc"):
output_path = input_path[:-4] + ".dec"
else:
output_path = input_path + ".dec"
with open(output_path, "wb") as f:
f.write(decrypted_data)
print(f"File decrypted successfully -> {output_path}")
def show_menu():
print("\n===== File Encryption / Decryption Tool =====")
print("1. Encrypt a file")
print("2. Decrypt a file")
print("3. Exit")
def main():
generate_key()
while True:
show_menu()
choice = input("Enter your choice (1-3): ").strip()
if choice == "1":
path = input("Enter the path of the file to encrypt: ").strip()
encrypt_file(path)
elif choice == "2":
path = input("Enter the path of the file to decrypt: ").strip()
decrypt_file(path)
elif choice == "3":
print("Exiting the program. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please select between 1 and 3.")
if __name__ == "__main__":
main()