Created
January 27, 2022 16:37
-
-
Save fritschy/452bfb5b2294f3b47c62402bf608d489 to your computer and use it in GitHub Desktop.
Check if password is pwned
This file contains 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 python3 | |
import hashlib | |
import sys | |
import getpass | |
import urllib.request | |
import re | |
class colors: | |
red='\033[91m' | |
normal='\033[0m' | |
def flag_in_args(*args): return any(map(lambda x: x in ARGS, args)) | |
ARGS = sys.argv[1:] | |
VERBOSE = flag_in_args('-v', '--verbose') | |
OUTPUT = sys.stdout.isatty() | |
PWNED = re.subn('(_+)', colors.normal+r'\1'+colors.red, r''' | |
__/\\\\\\\\\\\\\____/\\\______________/\\\__/\\\\\_____/\\\__/\\\\\\\\\\\\\\\__/\\\\\\\\\\\\____ | |
_\/\\\/////////\\\_\/\\\_____________\/\\\_\/\\\\\\___\/\\\_\/\\\///////////__\/\\\////////\\\__ | |
_\/\\\_______\/\\\_\/\\\_____________\/\\\_\/\\\/\\\__\/\\\_\/\\\_____________\/\\\______\//\\\_ | |
_\/\\\\\\\\\\\\\/__\//\\\____/\\\____/\\\__\/\\\//\\\_\/\\\_\/\\\\\\\\\\\_____\/\\\_______\/\\\_ | |
_\/\\\/////////_____\//\\\__/\\\\\__/\\\___\/\\\\//\\\\/\\\_\/\\\///////______\/\\\_______\/\\\_ | |
_\/\\\_______________\//\\\/\\\/\\\/\\\____\/\\\_\//\\\/\\\_\/\\\_____________\/\\\_______\/\\\_ | |
_\/\\\________________\//\\\\\\//\\\\\_____\/\\\__\//\\\\\\_\/\\\_____________\/\\\_______/\\\__ | |
_\/\\\_________________\//\\\__\//\\\______\/\\\___\//\\\\\_\/\\\\\\\\\\\\\\\_\/\\\\\\\\\\\\/___ | |
_\///___________________\///____\///_______\///_____\/////__\///////////////__\////////////_____ | |
''')[0]+colors.normal | |
def readpass(): | |
p = getpass.getpass() if sys.stdin.isatty() else sys.stdin.read() | |
if len(p) == 0: | |
sys.exit(1) | |
return p | |
def sha1(pwstr): | |
return hashlib.sha1(pwstr.encode('utf-8')).hexdigest().upper() | |
def pr(*args): | |
if OUTPUT: | |
print(*args) | |
def HIBP(digest): | |
d5 = digest[:5], digest[5:] | |
url = 'https://api.pwnedpasswords.com/range/' + d5[0] | |
headers = {'User-Agent': 'Mozilla/5.0 (Linux; X11)'} | |
req = urllib.request.Request(url, headers=headers) | |
if VERBOSE: | |
pr('GET ' + url) | |
with urllib.request.urlopen(req) as r: | |
html = r.read().decode('utf-8')[1:] | |
hashes = dict(map(lambda x: x.split(':'), html.split('\r\n'))) | |
if VERBOSE: | |
pr('%d hashes' % len(hashes)) | |
if d5[1] in hashes: | |
return int(hashes[d5[1]]) | |
return 0 | |
def main(): | |
times = HIBP(sha1(readpass())) | |
if times != 0: | |
if sys.stdout.isatty(): | |
times = 'once' if times == 1 else '%d times' % times | |
pr(PWNED) | |
pr("(%s)" % times) | |
sys.exit(1) | |
pr('OK') | |
__name__ == '__main__' and main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment