Skip to content

Instantly share code, notes, and snippets.

@ilanschnell
Created June 27, 2022 04:31
Show Gist options
  • Save ilanschnell/6df6d201c9d31aea3ffd0798f430d9ad to your computer and use it in GitHub Desktop.
Save ilanschnell/6df6d201c9d31aea3ffd0798f430d9ad to your computer and use it in GitHub Desktop.
Python interface for https://api.pwnedpasswords.com/
import hashlib
import urllib.request
def lookup_passwd(passwd: str, verbose: bool=False) -> int:
# see: https://haveibeenpwned.com/API/v3#PwnedPasswords
sha1passwd = hashlib.sha1(passwd.encode()).hexdigest().upper()
head, tail = sha1passwd[:5], sha1passwd[5:]
url = 'https://api.pwnedpasswords.com/range/' + head
with urllib.request.urlopen(url) as f:
lines = f.read().decode().split()
if verbose:
print("sha1: %s" % sha1passwd)
print("lines: %d" % len(lines))
for line in lines:
t, count = line.split(':')
if t == tail:
return int(count)
return None
def main():
from optparse import OptionParser
p = OptionParser(
usage="usage: %prog [options] password [password ...]",
description="Check if password has been pwned.")
p.add_option('-v', "--verbose",
action="store_true")
opts, args = p.parse_args()
for passwd in args:
count = lookup_passwd(passwd, opts.verbose)
if count is None:
print("%r was not found" % passwd)
else:
print("%r was found with %d occurrences" % (passwd, count))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment