Last active
November 10, 2022 00:33
-
-
Save n05tr0m0/e5015fb6fd68809ef2ac2e8b3032f392 to your computer and use it in GitHub Desktop.
Python Password Generator
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
# taken from https://stackoverflow.com/questions/9594125/salt-and-hash-a-password-in-python/56915300#56915300 | |
import hashlib | |
import hmac | |
import os | |
def hash_new_password(password: str) -> tuple[bytes, bytes]: | |
""" | |
Hash the provided password with a randomly-generated salt and return the | |
salt and hash to store in the database. | |
""" | |
salt = os.urandom(16) | |
pw_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000) | |
return salt, pw_hash | |
def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool: | |
""" | |
Given a previously-stored salt and hash, and a password provided by a user | |
trying to log in, check whether the password is correct. | |
""" | |
return hmac.compare_digest( | |
pw_hash, | |
hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000) | |
) | |
# Example usage: | |
salt, pw_hash = hash_new_password('correct horse battery staple') | |
assert is_correct_password(salt, pw_hash, 'correct horse battery staple') | |
assert not is_correct_password(salt, pw_hash, 'Tr0ub4dor&3') | |
assert not is_correct_password(salt, pw_hash, 'rosebud') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment