-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsecurity.py
70 lines (49 loc) · 1.69 KB
/
security.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
"""
Security module for SafePass
This module contains functions that utilize the argon2-cffi and the cryptography libraries
argon2-cffi: https://argon2-cffi.readthedocs.io/en/stable/argon2.html
cryptography: https://cryptography.io/en/latest/
"""
import base64
from argon2 import PasswordHasher, exceptions
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
ph = PasswordHasher()
def generate_hash(password: str) -> str:
"""Create argon2 hash using default parameters"""
return ph.hash(password)
def check_password(hash: str, password: str) -> bool:
"""Check if provided password matches hash"""
try:
ph.verify(hash, password)
return True
except exceptions.VerifyMismatchError:
return False
def check_rehash(hash: str) -> bool:
"""Check if hash parameters are outdated"""
if ph.check_needs_rehash(hash):
return True
return False
def derive_key(password: str, salt: bytes) -> bytes:
"""Derive a secure key for encryption"""
password = password.encode('utf-8')
# Key derivation function setup
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=600000,
)
# Key to realize encryption
key = base64.urlsafe_b64encode(kdf.derive(password))
return key
def encrypt(key: Fernet, data: str) -> bytes:
"""Encrypt data with Fernet key"""
data = data.encode('utf-8')
token = key.encrypt(data)
return token
def decrypt(key: Fernet, token: bytes) -> bytes:
"""Decrypt data with Fernet key"""
data = key.decrypt(token)
return data