Created
December 14, 2022 11:20
-
-
Save gwo0d/5793caa0b990bfe04cbead85d880144c to your computer and use it in GitHub Desktop.
A nice, secure, simple User class using salted SHA3-512 and implemented in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import secrets | |
class User: | |
""" | |
A class to represent a user. | |
========================= | |
Attributes: | |
---------- | |
first_name: str | |
first name of the user | |
last_name: str | |
last name of the user | |
email: str | |
email address of the user | |
username: str | |
username for the user | |
password: str | |
password for the user | |
Methods: | |
---------- | |
get_user_details(password) -> dict: | |
returns a dictionary of the user's details if password is correct, otherwise None. | |
check_password(password: str) -> bool: | |
returns True if the password is correct for the user, otherwise False. | |
change_password(password: str, new_password: str) -> bool: | |
returns True if password changed, otherwise False. | |
""" | |
MINIMUM_PASSWORD_LENGTH = 12 | |
__SALT_LENGTH = 256 | |
def __init__(self, first_name: str, last_name: str, email: str, username: str, password: str) -> None: | |
self.__first_name = first_name | |
self.__last_name = last_name | |
self.__email = email | |
self.__username = username | |
if len(password) >= self.MINIMUM_PASSWORD_LENGTH: | |
self.__password = self.__hash_password(password) | |
else: | |
raise ValueError(f"The password must be at least {self.MINIMUM_PASSWORD_LENGTH} characters.") | |
def __hash_password(self, password: str) -> dict: | |
p = password.encode('UTF-8') | |
s = str(secrets.randbits(self.__SALT_LENGTH)).encode('UTF-8') | |
h = hashlib.sha3_512() | |
h.update(p) | |
h.update(s) | |
d = { | |
'hash': h.hexdigest(), | |
'salt': s | |
} | |
return d | |
def get_user_details(self, password: str) -> dict: | |
if self.check_password(password): | |
d = { | |
'first_name': self.__first_name, | |
'last_name': self.__last_name, | |
'email': self.__email, | |
'username': self.__username | |
} | |
return d | |
def check_password(self, password: str) -> bool: | |
p = password.encode('UTF-8') | |
s = self.__password['salt'] | |
h = hashlib.sha3_512() | |
h.update(p) | |
h.update(s) | |
if h.hexdigest() == self.__password['hash']: | |
return True | |
else: | |
return False | |
def change_password(self, password: str, new_password: str) -> bool: | |
if self.check_password(password): | |
self.__password = self.__hash_password(new_password) | |
return True | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment