tabpy.tabpy_server.handlers.util.hash_password()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 28
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 28
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nop 2
crap 1
1 1
import binascii
2 1
from hashlib import pbkdf2_hmac
3 1
from enum import Enum, auto
4
5
6 1
class AuthErrorStates(Enum):
7 1
    NONE = auto()
8 1
    NotAuthorized = auto()
9 1
    NotRequired = auto()
10
11 1
def hash_password(username, pwd):
12
    """
13
    Hashes password using PKDBF2 method:
14
    hash = PKDBF2('sha512', pwd, salt=username, 10000)
15
16
    Parameters
17
    ----------
18
    username : str
19
        User name (login). Used as salt for hashing.
20
        User name is lowercased befor being used in hashing.
21
        Salt is formatted as '_$salt@tabpy:<username>$_' to
22
        guarantee there's at least 16 characters.
23
24
    pwd : str
25
        Password to hash.
26
27
    Returns
28
    -------
29
    str
30
        Sting representation (hexidecimal) for PBKDF2 hash
31
        for the password.
32
    """
33 1
    salt = f"_$salt@tabpy:{username.lower()}$_"
34
35 1
    hash = pbkdf2_hmac(
36
        hash_name="sha512", password=pwd.encode(), salt=salt.encode(), iterations=10000
37
    )
38
    return binascii.hexlify(hash).decode()
39