-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto_utils.py
More file actions
28 lines (21 loc) · 807 Bytes
/
crypto_utils.py
File metadata and controls
28 lines (21 loc) · 807 Bytes
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
from cryptography.fernet import Fernet
import hashlib
import os
import base64
def generate_key(password):
return hashlib.sha256(password.encode()).digest()
def encrypt_file(filepath, password):
key = generate_key(password)
f = Fernet(base64.urlsafe_b64encode(key))
with open(filepath, 'rb') as file:
data = file.read()
filename = os.path.basename(filepath)
with open("../locker/" + filename, 'wb') as enc:
enc.write(f.encrypt(data))
def decrypt_file(filename, password):
key = generate_key(password)
f = Fernet(base64.urlsafe_b64encode(key))
with open("../locker/" + filename, 'rb') as file:
encrypted = file.read()
with open("../decrypted_" + filename, 'wb') as dec:
dec.write(f.decrypt(encrypted))