Skip to content

Instantly share code, notes, and snippets.

@born2discover
Created May 11, 2021 22:53
Show Gist options
  • Save born2discover/72588faa8bd898d6e70e1bc1bde5c0e1 to your computer and use it in GitHub Desktop.
Save born2discover/72588faa8bd898d6e70e1bc1bde5c0e1 to your computer and use it in GitHub Desktop.
Check a password against pwned passwords API using k-Anonymity. https://haveibeenpwned.com/API/v3
def pwned(password):
"""
Check password against pwnedpasswords API using k-Anonymity.
https://haveibeenpwned.com/API/v3
:return: Count of password in DB (0 means hasn't been compromised)
Can raise HTTPError
.. versionadded:: 3.4.0
"""
def convert_password_tuple(value):
hash_suffix, count = value.split(":")
return hash_suffix, int(count)
sha1 = hashlib.sha1(password.encode("utf8")).hexdigest()
req = urllib.request.Request(
url=f"https://api.pwnedpasswords.com/range/{sha1[:5].upper()}",
headers={"User-Agent": "Flask-Security (Python)"},
)
# Might raise HTTPError
with urllib.request.urlopen(req) as f:
response = f.read()
raw = response.decode("utf-8-sig")
entries = dict(map(convert_password_tuple, raw.upper().split("\r\n")))
return entries.get(sha1[5:].upper(), 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment