git-subtree-dir: gerenciador git-subtree-mainline:f4f546c928git-subtree-split:34cc9c75a5
32 lines
1.0 KiB
Python
32 lines
1.0 KiB
Python
"""
|
|
Hash de senha de funcionário com scrypt (hashlib da biblioteca padrão —
|
|
sem dependência extra tipo bcrypt/passlib). Formato armazenado:
|
|
"scrypt$<salt em hex>$<hash em hex>".
|
|
"""
|
|
import hashlib
|
|
import secrets
|
|
|
|
_N, _R, _P = 2**14, 8, 1
|
|
_TAMANHO_HASH = 32
|
|
|
|
|
|
def gerar_hash(senha: str) -> str:
|
|
salt = secrets.token_bytes(16)
|
|
resultado = hashlib.scrypt(senha.encode("utf-8"), salt=salt, n=_N, r=_R, p=_P, dklen=_TAMANHO_HASH)
|
|
return f"scrypt${salt.hex()}${resultado.hex()}"
|
|
|
|
|
|
def verificar_senha(senha: str, hash_armazenado: str) -> bool:
|
|
"""Nunca lança — hash malformado ou senha errada só retorna False."""
|
|
try:
|
|
algoritmo, salt_hex, hash_hex = hash_armazenado.split("$")
|
|
if algoritmo != "scrypt":
|
|
return False
|
|
salt = bytes.fromhex(salt_hex)
|
|
esperado = bytes.fromhex(hash_hex)
|
|
except (ValueError, AttributeError):
|
|
return False
|
|
|
|
calculado = hashlib.scrypt(senha.encode("utf-8"), salt=salt, n=_N, r=_R, p=_P, dklen=len(esperado))
|
|
return secrets.compare_digest(calculado, esperado)
|