-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.py
More file actions
45 lines (41 loc) · 1.5 KB
/
encryption.py
File metadata and controls
45 lines (41 loc) · 1.5 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
from cryptography.fernet import Fernet
import os
# File to store the encryption key
KEY_FILE = "encryption.key"
# Generate or load the encryption key
def load_key():
if not os.path.exists(KEY_FILE):
key = Fernet.generate_key()
with open(KEY_FILE, "wb") as key_file:
key_file.write(key)
else:
with open(KEY_FILE, "rb") as key_file:
key = key_file.read()
return Fernet(key)
# Encrypt a file
def encrypt_file(file_path):
cipher = load_key()
if os.path.exists(file_path):
with open(file_path, "rb") as file:
data = file.read()
encrypted_data = cipher.encrypt(data)
with open(file_path, "wb") as file:
file.write(encrypted_data)
print(f"File '{file_path}' encrypted successfully.")
# Decrypt a file
def decrypt_file(file_path):
cipher = load_key()
if os.path.exists(file_path):
with open(file_path, "rb") as file:
encrypted_data = file.read()
try:
# Attempt to decrypt the file
decrypted_data = cipher.decrypt(encrypted_data)
with open(file_path, "wb") as file:
file.write(decrypted_data)
print(f"File '{file_path}' decrypted successfully.")
except Exception as e:
# If decryption fails, assume the file is already in plaintext
print(f"File '{file_path}' is not encrypted or decryption failed: {e}")
else:
print(f"File '{file_path}' does not exist. Cannot decrypt.")