Skip to content

Instantly share code, notes, and snippets.

@nils-werner
Last active March 2, 2018 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nils-werner/0c1679435e1a79988984a27e80a55982 to your computer and use it in GitHub Desktop.
Save nils-werner/0c1679435e1a79988984a27e80a55982 to your computer and use it in GitHub Desktop.
Have I Been Pwned Password Checker
#!/usr/bin/env python
from __future__ import print_function
import sys
import getpass
import hashlib
import argparse
try:
# Python 3
from urllib.request import Request, urlopen
except ImportError:
# Python 2
from urllib2 import Request, urlopen
input = raw_input
def confirm_choice(msg):
confirm = None
while confirm is None:
val = input("{} Confirm? [Y/n] ".format(msg)).upper()
if val in ('', 'Y'):
confirm = True
elif val in ('N',):
confirm = False
return confirm
parser = argparse.ArgumentParser()
parser.add_argument(
'-y', '--yes', action='store_true'
)
args = parser.parse_args()
print(
"I will never transmit your password, but only the first "
"5 characters of its SHA1 sum."
)
pwd = getpass.getpass("Enter Password: ")
shasum = hashlib.sha1(pwd.encode('utf-8')).hexdigest().upper()
headers = {
'User-Agent': 'python-script-hibp',
}
if args.yes:
print("I will send {} to pwnedpasswords.com.".format(shasum[:5]))
else:
if not confirm_choice(
"I will send {} to pwnedpasswords.com.".format(shasum[:5])
):
sys.exit(-1)
q = Request("https://api.pwnedpasswords.com/range/{}".format(shasum[:5]))
q.add_header('User-Agent', 'python-script-hibp')
retval = urlopen(q).read().decode("utf-8")
for line in retval.splitlines():
foundsum, foundno = line.split(":")
foundno = int(foundno)
if shasum[5:] == foundsum:
print("Password has been pwned {} times".format(foundno))
sys.exit(foundno)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment