Last active
March 2, 2018 12:21
-
-
Save nils-werner/0c1679435e1a79988984a27e80a55982 to your computer and use it in GitHub Desktop.
Have I Been Pwned Password Checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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