File size: 901 Bytes
478dec6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import hashlib
from config.constant import SecurityConstants
from passlib.hash import bcrypt


def _prepare_password(password: str) -> bytes:
    password_bytes = password.encode("utf-8")

    # SHA-256 = 32 bytes (ALWAYS < 72)
    digest = hashlib.sha256(password_bytes).digest()

    # This slice is technically redundant, but explicit
    return digest[:SecurityConstants.BCRYPT_MAX_BYTES]


def hash_password(password: str) -> str:
    prepared = _prepare_password(password)

    # ASSERTION (fail fast if something is wrong)
    assert len(prepared) <= 72, f"bcrypt input too long: {len(prepared)} bytes"

    return bcrypt.hash(prepared)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    prepared = _prepare_password(plain_password)

    assert len(prepared) <= 72, f"bcrypt input too long: {len(prepared)} bytes"

    return bcrypt.verify(prepared, hashed_password)