-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.py
70 lines (57 loc) · 1.68 KB
/
encrypt.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
import os
from cryptography.fernet import Fernet
def write_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Loads the key from the current directory named `key.key`
"""
return open("key.key", "rb").read()
def decrypt(filename, key):
"""
Given a filename (str) and key (bytes), it decrypts the file and write it
"""
output_file = os.path.splitext(filename)[0] + "_decrypted" + ".flac"
input_file = os.path.splitext(filename)[0] + ".encrypted"
f = Fernet(key)
with open(input_file, "rb") as file:
# read the encrypted data
encrypted_data = file.read()
# decrypt data
decrypted_data = f.decrypt(encrypted_data)
# write the original file
with open(output_file, "wb") as file:
file.write(decrypted_data)
def encrypt(filename, key, data):
"""
Given a filename (str) and key (bytes), it encrypts the file and write it
"""
output_file = os.path.splitext(filename)[0] + ".encrypted"
f = Fernet(key)
"""with open(filename, "rb") as file:
# read all file data
file_data = file.read()"""
# encrypt data
encrypted_data = f.encrypt(data)
# write the encrypted file
with open(output_file, "ab") as file:
file.write(encrypted_data)
if not os.path.exists("key.key"):
write_key()
if __name__ == "__main__":
# write_key()
key = load_key()
filename = input("filename>")
try:
encrypt(filename, key)
except:
pass
try:
decrypt(filename, key)
except Exception as e:
print(e)