Skip to content

Instantly share code, notes, and snippets.

@n05tr0m0
Last active November 10, 2022 00:33
Show Gist options
  • Save n05tr0m0/e5015fb6fd68809ef2ac2e8b3032f392 to your computer and use it in GitHub Desktop.
Save n05tr0m0/e5015fb6fd68809ef2ac2e8b3032f392 to your computer and use it in GitHub Desktop.
Python Password Generator
# 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