Securely checking if a password is compromised in Python

Checking if “123” is compromised and how many hits it would get.
import os
import hashlib
n_matches = 0
while True:
sha1 = hashlib.sha1()
sha1.update(os.urandom(10))
digest = sha1.hexdigest()
if digest[:3] == '000':
n_matches += 1
print(digest, n_matches)
if n_matches >= 5:
break
PWNEDURL = "https://api.pwnedpasswords.com/range/{}"sha1 = hashlib.sha1()
sha1.update(passwd.encode())
hex_digest = sha1.hexdigest().upper()
hex_digest_f5 = hex_digest[:5]
hex_digest_remaining = hex_digest[5:]
r = requests.get(PWNEDURL.format(hex_digest_f5))leaked_passwd_freq = defaultdict(int)
for passwd_freq in r.content.splitlines():
pass_parts = passwd_freq.split(b":")
passwd = pass_parts[0].decode()
freq = pass_parts[1]
leaked_passwd_freq[passwd] = int(freq)
$ python3 passcheck.py
Enter password:
WARNING: Your password is compromised with 1078184 hits in the compromised passwords database
*Under the hood Have I Been Pwned web portal uses the same k-anonymity protocol and API to check for compromised passwords.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store