Skip to content

Instantly share code, notes, and snippets.

@arnar
Created August 21, 2012 23:33
Show Gist options
  • Save arnar/3420471 to your computer and use it in GitHub Desktop.
Save arnar/3420471 to your computer and use it in GitHub Desktop.
### Password hashing
def hash_pwd(pwd, salt=None, rounds=2**16):
"""Hashes a password using 2**16 rounds of SHA512 and a 64-bit salt.
The salt and hash result are concatenated and returned as a hexdigest.
"""
# Note: if this turns out to be too slow, consider using the py-bcrypt package
if salt is None:
# Note: Do not use python's random module for crypto!
salt = os.urandom(8)
else:
salt = salt[:16].decode('hex')
h = hashlib.sha512()
while rounds > 0:
h.update(salt)
h.update(pwd)
rounds -= 1
return salt.encode('hex') + h.hexdigest()
def verify_pwd(pwd, hashed):
return hash_pwd(pwd, hashed) == hashed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment