Skip to content

Instantly share code, notes, and snippets.

@Julien00859
Last active August 31, 2020 16:15
Show Gist options
  • Save Julien00859/012607983ca8a557d0714944accaee65 to your computer and use it in GitHub Desktop.
Save Julien00859/012607983ca8a557d0714944accaee65 to your computer and use it in GitHub Desktop.
Password hardening mini lib
import secrets
import hashlib
def harden_pwd(pwd: str, version=1) -> bytes:
# scrypt n factor should be at least 2<<15 for interfactive usage,
# oddly enough, a n value higher than 2<<13 doesn't work on my machine
# https://blog.filippo.io/the-scrypt-parameters/
if version == 1:
salt = secrets.token_urlsafe(16).encode() # so there is no $ symbol
hardened = hashlib.scrypt(pwd.encode(), salt=salt, n=2<<13, r=8, p=1)
return b"$1$" + salt + b"$" + hardened # /etc/shadow like formatting
else:
raise ValueError("Cannot harden type %d password" % version)
def verify_pwd(pwd: str, shadow: bytes) -> bool:
_, version, salt, truth_hardened = shadow.split(b'$', 3)
if version == b"1":
hardened = hashlib.scrypt(pwd.encode(), salt=salt, n=2<<13, r=8, p=1)
return secrets.compare_digest(hardened, truth_hardened)
else:
raise ValueError("Cannot verify type %s password" % version.decode())
if __name__ == '__main__':
import sys
if '--test' in sys.argv:
shadow = harden_pwd("Test1234")
assert verify_pwd("Test1234", shadow)
assert not verify_pwd("Youplaboom", shadow)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment