-
Notifications
You must be signed in to change notification settings - Fork 0
/
endec.py
executable file
·78 lines (48 loc) · 1.83 KB
/
endec.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
#!/usr/bin/env python3
import argparse
from cryptography.fernet import Fernet
def print_banner():
print(r"""
____
___ ____ / __ \___ _____
/ _ \/ __ \/ / / / _ \/ ___/
/ __/ / / / /_/ / __/ /__
\___/_/ /_/_____/\___/\___/
""")
def get_args():
parser = argparse.ArgumentParser(description="Encrypt/Decrypt files")
parser.add_argument("command", help="encrypt/decrypt")
parser.add_argument("file", help="file to be encrypted/decrypted")
parser.add_argument("-k", "--key", help="secret key for decryption")
args = parser.parse_args()
if args.command == "decrypt" and not args.key:
parser.error("enter the secret key for decryption")
return args
def encrypt_file(file):
key = Fernet.generate_key()
with open(file, "rb") as read_file:
content = read_file.read()
encrypted_content = Fernet(key).encrypt(content)
with open(file, "wb") as write_file:
write_file.write(encrypted_content)
key = key.decode("utf-8")
print(f"The file {file} has been encrypted with the secret key {key}\nKeep it safe for decryption")
def decrypt_file(file, key):
with open(file, "rb") as read_file:
encrypted_content = read_file.read()
decrypted_content = Fernet(key).decrypt(encrypted_content)
with open(file, "wb") as write_file:
write_file.write(decrypted_content)
print(f"The file {file} has been decrypted")
def main():
print_banner()
args = get_args()
if (args.command == "encrypt"):
encrypt_file(args.file)
if (args.command == "decrypt"):
try:
decrypt_file(args.file, args.key)
except:
print("Wrong secret key")
if __name__ == "__main__":
main()