-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode
More file actions
52 lines (46 loc) · 1.65 KB
/
code
File metadata and controls
52 lines (46 loc) · 1.65 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
from cryptography.fernet import Fernet
import os
def generate_key():
key = Fernet.generate_key()
with open("Secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
return open("Secret.key", "rb").read()
def encrypt(filename, key):
f = Fernet(key)
with open(filename, "rb") as file:
file_data = file.read()
encrypted_data = f.encrypt(file_data)
with open(filename, "wb") as file:
file.write(encrypted_data)
def decrypt(filename, key):
f = Fernet(key)
with open(filename, "rb") as file:
encrypted_data = file.read()
try:
decrypted_data = f.decrypt(encrypted_data)
except InvalidToken:
print("Invalid key")
return
with open(filename, "wb") as file:
file.write(decrypted_data)
choice = input("Enter 'E' to encrypt or 'D' decrypt the file.").lower()
if choice == 'e':
filename = input("Enter the file name to encrypt(including file extension):")
if os.path.exists(filename):
generate_key()
key=load_key()
encrypt(filename, key)
print("File Encrypted Successfully!!!")
else:
print(f"file '{filename}' not found. Please check the file name and try again.")
elif choice == "d":
filename = input("Enter the file name to encrypt(including file extension):")
if os.path.exists(filename):
key=load_key()
decrypt(filename, key)
print("File Decrypted Successfully!!!")
else:
print(f"file '{filename}' not found. Please check the file name and try again.")
else:
print("Invalid choice. Please enter 'E' to encrypt a file or 'D' to decrypt a file")