-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
49 lines (34 loc) · 1.43 KB
/
main.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
from cryptography.fernet import Fernet
def generate_key() -> bytes:
return Fernet.generate_key()
def save_key(key: bytes, key_file: str) -> None:
with open(key_file, 'wb') as file:
file.write(key)
def load_key(key_file: str) -> bytes:
with open(key_file, 'rb') as file:
return file.read()
def encrypt_file(input_file: str, output_file: str, key: bytes) -> None:
with open(input_file, 'rb') as file:
data = file.read()
fernet: Fernet = Fernet(key)
encrypted_data: bytes = fernet.encrypt(data)
with open(output_file, 'wb') as file:
file.write(encrypted_data)
def decrypt_file(input_file: str, output_file: str, key: bytes) -> None:
with open(input_file, 'rb') as file:
encrypted_data = file.read()
fernet: Fernet = Fernet(key)
decrypted_data: bytes = fernet.decrypt(encrypted_data)
with open(output_file, 'wb') as file:
file.write(decrypted_data)
if __name__ == "__main__":
key: bytes = generate_key()
key_file: str = 'encrypted_key.key'
save_key(key, key_file)
input_file: str = 'something.txt'
encrypted_file: str = 'encrypted_file.txt'
decrypted_file: str = 'decrypted_file.txt'
encrypt_file(input_file, encrypted_file, key)
print(f"File '{encrypted_file}' decrypted to '{encrypted_file}'")
decrypt_file(encrypted_file, decrypted_file, key)
print(f"File '{encrypted_file}' decrypted to '{decrypted_file}'")