Last active
January 30, 2020 03:44
-
-
Save zhangzhhz/47e6947901649db319792c585b7340ff to your computer and use it in GitHub Desktop.
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
import hashlib, binascii, os | |
def hash_password(password): | |
"""Hash a password for storing.""" | |
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii') | |
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), | |
salt, 100000) | |
pwdhash = binascii.hexlify(pwdhash) | |
return (salt + pwdhash).decode('ascii') | |
def verify_password(stored_password, provided_password): | |
"""Verify a stored password against one provided by user""" | |
salt = stored_password[:64] | |
stored_password = stored_password[64:] | |
pwdhash = hashlib.pbkdf2_hmac('sha512', | |
provided_password.encode('utf-8'), | |
salt.encode('ascii'), | |
100000) | |
pwdhash = binascii.hexlify(pwdhash).decode('ascii') | |
return pwdhash == stored_password | |
stored_password = hash_password('ThisIsAPassWord') | |
print(stored_password) # 76002b01430da6b4d8686468ec2b3f6989b686b2dacb8cf35e86825bd230c2568b74f4251da100c7110af497de5046e470bf4b93fbb3358e3ead08a65c536f989769e517f91903fbfc95958fb687f2ddf547e26b1a53421dbb52f457ffdcc95a | |
verify_password(stored_password, 'ThisIsAPassWord') # True | |
verify_password(stored_password, 'WrongPassword') # False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment