This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilecrypt.py
63 lines (50 loc) · 1.42 KB
/
filecrypt.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
from cryptography.fernet import Fernet
import sys
import os
import gzip
keyfile = 'crypt.key'
key = None
def main():
if len(sys.argv) < 3:
print('usage: python filecrypt.py <file> <mode>')
print(' <mode> can be "e" (encode) or "d" (decode)')
return
file = sys.argv[1]
mode = sys.argv[2]
print("File: " + file)
if os.path.isfile(keyfile):
key = load_key()
else:
key = write_key()
if mode == "e":
print('Mode: Encrypt')
encrypt(file, key)
elif mode == "d":
print('Mode: Decrypt')
decrypt(file, key)
else:
print('<mode> can be only "e" or "d"')
def write_key():
key = Fernet.generate_key()
with open(keyfile, 'wb') as key_file:
key_file.write(key)
return key
def load_key():
key = open(keyfile, 'rb').read()
return key
def encrypt(filename, key):
f = Fernet(key)
with open(filename, 'rb') as file:
file_data = file.read()
encrypted_data = gzip.compress(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()
decrypted_data = f.decrypt(gzip.decompress(encrypted_data))
with open(filename, 'wb') as file:
file.write(decrypted_data)
if __name__ == '__main__':
main()