Roudrigus commited on
Commit
eeb2ebb
·
verified ·
1 Parent(s): a050b5d

Update utils_seguranca.py

Browse files
Files changed (1) hide show
  1. utils_seguranca.py +37 -14
utils_seguranca.py CHANGED
@@ -1,14 +1,37 @@
1
- import bcrypt
2
-
3
-
4
- def gerar_hash_senha(senha: str) -> str:
5
- senha_bytes = senha.encode("utf-8")
6
- hash_bytes = bcrypt.hashpw(senha_bytes, bcrypt.gensalt())
7
- return hash_bytes.decode("utf-8")
8
-
9
-
10
- def verificar_senha(senha_digitada: str, senha_hash: str) -> bool:
11
- return bcrypt.checkpw(
12
- senha_digitada.encode("utf-8"),
13
- senha_hash.encode("utf-8")
14
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils_seguranca.py
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import bcrypt
5
+
6
+ def gerar_hash_senha(senha: str) -> str:
7
+ """
8
+ Gera hash seguro usando bcrypt.
9
+ • Retorna string UTF-8.
10
+ Protege contra entrada vazia.
11
+ """
12
+ if not senha:
13
+ raise ValueError("A senha não pode ser vazia ao gerar hash.")
14
+ senha_bytes = senha.encode("utf-8")
15
+ hash_bytes = bcrypt.hashpw(senha_bytes, bcrypt.gensalt())
16
+ return hash_bytes.decode("utf-8")
17
+
18
+
19
+ def verificar_senha(senha_digitada: str, senha_hash: str) -> bool:
20
+ """
21
+ Verifica senha usando bcrypt.
22
+ • Suporta fallback seguro quando o hash estiver vazio, None ou inválido.
23
+ • Nunca lança exceção — sempre retorna True/False.
24
+ """
25
+ try:
26
+ if not senha_digitada or not senha_hash:
27
+ return False
28
+
29
+ senha_bytes = senha_digitada.encode("utf-8")
30
+ hash_bytes = senha_hash.encode("utf-8")
31
+
32
+ return bcrypt.checkpw(senha_bytes, hash_bytes)
33
+
34
+ except Exception:
35
+ # Exemplo de erros pegos: hash truncado, hash malformado,
36
+ # tipos incorretos vindo do banco, conversão unicode, etc.
37
+ return False