'''
py_pwnedpasswords: a Python code to detect Pwned Passwords

Author: Roberto Rossi

MIT License (https://opensource.org/licenses/MIT)
  
Copyright (c) 2022 Roberto Rossi

The code is based on https://api.pwnedpasswords.com/ and provides a minimalistic implementation of the discussion in https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/

The procedure implemented ensures privacy via k-Anonymity, for more information on how privacy of checked passwords is safeguarded see https://blog.cloudflare.com/validating-leaked-passwords-with-k-anonymity/
'''

import hashlib
import urllib
from urllib.request import urlopen 

pwd = 'P@ssw0rd' # the password to be checked

# compute the hash (SHA-1) of the password
hash = hashlib.sha1(bytes(pwd, 'utf-8')).hexdigest()  

# split the hash into a head comprising 5 characters, 
# and a tail with the rest of the hash
head, tail = hash[0:5].upper(), hash[5:].upper()   

# retrieve list of pwned password hash tails matching the head
link = "https://api.pwnedpasswords.com/range/" + head 
tails = urllib.request.urlopen(link).read() 

if tail not in tails.decode("utf-8"):
  print("Password \"" + pwd + "\" has not been pwned")
else: 
  for item in tails.decode("utf-8").split("\n"):      
    if tail in item: 
      n = item.strip().split(":")[1] # retrieve pwned count
  print("Password \"" + pwd + "\" has been pwned " + n + " times.")
