-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto_utils.py
More file actions
78 lines (68 loc) · 2.36 KB
/
crypto_utils.py
File metadata and controls
78 lines (68 loc) · 2.36 KB
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
import os
import base64
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.fernet import Fernet
def _derive_key(password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
backend=default_backend()
)
return base64.urlsafe_b64encode(kdf.derive(password.encode()))
def encrypt_file_with_password(filepath: str, password: str, salt: bytes = None):
"""
Crittografa il file specificato usando la password fornita.
Il salt viene salvato come primi 16 byte del file cifrato.
"""
if salt is None:
salt = os.urandom(16)
key = _derive_key(password, salt)
f = Fernet(key)
with open(filepath, 'rb') as file:
data = file.read()
encrypted = f.encrypt(data)
with open(filepath + '.enc', 'wb') as file:
file.write(salt + encrypted)
def decrypt_file_with_password(filepath: str, password: str, output_path: str = None):
"""
Decrittografa il file cifrato (che deve avere i primi 16 byte come salt).
Se output_path non è specificato, rimuove ".enc" dal nome file.
"""
with open(filepath, 'rb') as file:
salt = file.read(16)
encrypted = file.read()
key = _derive_key(password, salt)
f = Fernet(key)
decrypted = f.decrypt(encrypted)
if output_path is None:
if filepath.endswith('.enc'):
output_path = filepath[:-4]
else:
output_path = filepath + '.dec'
with open(output_path, 'wb') as file:
file.write(decrypted)
import io
def encrypt_bytes_with_password(data: bytes, password: str, salt: bytes = None) -> bytes:
"""
Crittografa i bytes passati usando la password fornita.
Il salt viene prepended ai dati cifrati (primi 16 byte).
"""
if salt is None:
salt = os.urandom(16)
key = _derive_key(password, salt)
f = Fernet(key)
encrypted = f.encrypt(data)
return salt + encrypted
def decrypt_bytes_with_password(data: bytes, password: str) -> bytes:
"""
Decrittografa i bytes passati (primi 16 byte = salt).
"""
salt = data[:16]
encrypted = data[16:]
key = _derive_key(password, salt)
f = Fernet(key)
return f.decrypt(encrypted)