blob: 9430c05753469f84c606089c4599bf9adaa540ac [file] [log] [blame]
escaleirae67809a2025-04-03 18:53:24 +01001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13# implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17
18from hashlib import sha256
19import bcrypt
20
21
22def hash_password(password: str, rounds: int = 12) -> str:
23 """
24 Hash a password with a given number of rounds and return as hex.
25
26 Args:
27 - password (str): The password to hash.
28 - rounds (int): The number of rounds (log_rounds) for bcrypt. Default is 12.
29
30 Returns:
31 - str: The hashed password as an hex string.
32 """
33 # Generate a salt with the specified number of rounds
34 salt = bcrypt.gensalt(rounds=rounds)
35
36 # Hash the password using the generated salt
37 hashed_password = bcrypt.hashpw(password.encode("utf-8"), salt)
38
39 # Return the hashed password and salt as hex strings
40 return hashed_password.hex()
41
42
43def verify_password(password: str, hashed_password_hex: str) -> bool:
44 """
45 Verify a password against a hashed password provided as hex.
46
47 Args:
48 - password (str): The password to verify.
49 - hashed_password_hex (str): The hashed password as a hex string.
50
51 Returns:
52 - bool: True if the password matches the hashed password, False otherwise.
53 """
54 # Convert the hashed password from hex to bytes
55 hashed_password = bytes.fromhex(hashed_password_hex)
56
57 # Verify the password against the hashed password
58 return bcrypt.checkpw(password.encode("utf-8"), hashed_password)
59
60
61def verify_password_sha256(password: str, hashed_password_hex: str, salt: str) -> bool:
62 """
63 [Function for backwards compatibility using the SHA256]
64 Verify a password against a hashed password provided as hex.
65
66 Args:
67 - password (str): The password to verify.
68 - hashed_password_hex (str): The hashed password as a hex string.
69 - salt (str): The salt used to hash the password as a hex string.
70
71 Returns:
72 - bool: True if the password matches the hashed password, False otherwise.
73 """
74 # Old verification for backwards compatibility
75 shadow_password = sha256(
76 password.encode("utf-8") + salt.encode("utf-8")
77 ).hexdigest()
78
79 return shadow_password == hashed_password_hex