-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto_utils.py
More file actions
36 lines (31 loc) · 1003 Bytes
/
crypto_utils.py
File metadata and controls
36 lines (31 loc) · 1003 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
29
30
31
32
33
34
35
36
# crypto_utils.py
import base64
import os
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.fernet import Fernet
SALT_FILE = "vault.salt"
ITERATIONS = 390000
def get_salt() -> bytes:
if os.path.exists(SALT_FILE):
with open(SALT_FILE, 'rb') as f:
return f.read()
else:
salt = os.urandom(16)
with open(SALT_FILE, 'wb') as f:
f.write(salt)
return salt
def derive_key(password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=ITERATIONS,
backend=default_backend()
)
return base64.urlsafe_b64encode(kdf.derive(password.encode()))
def get_fernet(password: str) -> Fernet:
salt = get_salt()
key = derive_key(password, salt)
return Fernet(key)