Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Some notes for to make a simple/secure password hasher
import base64
import hashlib
import secrets
from typing import NoReturn
def pbkdf2(password: str, salt: str, iterations: int, dklen: int=0, digest=None):
"""Return the hash of password using pbkdf2."""
if digest is None:
digest = hashlib.sha256
dklen = dklen or None
password = password.encode()
salt = salt.encode()
return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
def encode_password(password: str, salt: str, iterations: int = 180000) -> NoReturn:
"""Encodes a password string to be compared later."""
assert salt and '$' not in salt
hash = pbkdf2(password, salt, iterations, digest=hashlib.sha256)
hash = base64.b64encode(hash).decode('ascii').strip()
return "%d$%s$%s" % (iterations, salt, hash)
def verify_password(password: str, encoded: str) -> bool:
"""Verify given password matchs the encoded version"""
iterations, salt, hash = encoded.split('$', 2)
encoded_2 = encode_password(password, salt, int(iterations))
return secrets.compare_digest(encoded.encode(), encoded_2.encode())
encoded = encode_password("hello", salt="SALT")
assert verify_password("hello", encoded) is True
assert verify_password("bye", encoded) is False

This comment has been minimized.

Copy link

@AdewumiIsaac AdewumiIsaac commented Dec 14, 2020

Fantastic code sir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment