Created
February 17, 2022 06:40
-
-
Save dastanozgeldi/ee97031e8b7731e4c782ea93d83a026a to your computer and use it in GitHub Desktop.
Just to introduce with the app logic
This file contains hidden or 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
| """Password managing algorithm""" | |
| import hashlib | |
| import hmac | |
| import bcrypt | |
| class PasswordManager: | |
| _log_rounds = 12 | |
| _prefix = '2b' | |
| _handle_long_passwords = False | |
| def _unicode_to_bytes(self, unicode_string): | |
| if isinstance(unicode_string, str): | |
| bytes_object = bytes(unicode_string, 'utf-8') | |
| else: | |
| bytes_object = unicode_string | |
| return bytes_object | |
| def generate_password_hash(self, password, rounds=None, prefix=None): | |
| if not password: | |
| raise ValueError('Password must be non-empty.') | |
| if rounds is None: | |
| rounds = self._log_rounds | |
| if prefix is None: | |
| prefix = self._prefix | |
| password = self._unicode_to_bytes(password) | |
| prefix = self._unicode_to_bytes(prefix) | |
| if self._handle_long_passwords: | |
| password = hashlib.sha256(password).hexdigest() | |
| password = self._unicode_to_bytes(password) | |
| salt = bcrypt.gensalt(rounds=rounds, prefix=prefix) | |
| return bcrypt.hashpw(password, salt) | |
| def check_password_hash(self, pw_hash, password): | |
| pw_hash = self._unicode_to_bytes(pw_hash) | |
| password = self._unicode_to_bytes(password) | |
| if self._handle_long_passwords: | |
| password = hashlib.sha256(password).hexdigest() | |
| password = self._unicode_to_bytes(password) | |
| return hmac.compare_digest(bcrypt.hashpw(password, pw_hash), pw_hash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment